PrevNext

示例:计算质数个数

重点例题 – 继续学习之前,请先尽力独立解决这道题!

这道题至少有两种解法。第一种解法的时间复杂度较高,但实现较简单;第二种解法的时间复杂度较低,但实现更复杂。

有关这些算法的更完整解释,请参阅这篇 CF 博客。

解法一

这种解法使用动态规划,其递推关系由筛法推导而来。

算法利用递推公式,迭代地减少不被质数整除的数的计数,时间复杂度为 O(N3/4log⁡N)O(\frac{N^{3/4}}{\sqrt{\log N}})。

代码实现

时间复杂度:O(N3/4log⁡N)O(\frac{N^{3/4}}{\sqrt{\log N}})

#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using ll = long long;
using std::cout;
using std::endl;
using std::pair;
using std::vector;

解法二

也存在 O(n2/3log⁡n3)O(\frac{n^{2/3}}{\sqrt[3]{\log n}}) 的实现;详情参见 Maksim1744 的 Codeforces 博客。下面给出一个使用树状数组的实现。请注意,这道 Library Checker 题目的最快解法看起来采用的是 O(N3/4log⁡N)O(\frac{N^{3/4}}{\sqrt{\log N}}) 的算法。

代码实现

时间复杂度:O(n2/3log⁡n3)O(\frac{n^{2/3}}{\sqrt[3]{\log n}})

#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using ll = long long;
using std::cout;
using std::endl;
using std::pair;
using std::vector;

练习题

StatusSourceProblem NameDifficultyTags
SPOJHard
Show TagsNumber Theory
YSHard
Show TagsNumber Theory
SPOJHard
Show TagsNumber Theory

Module Progress:

PrevNext