原题链接:https://leetcode.com/problems/count-primes/
我在github上的leetcode仓库:https://github.com/cooljacket/leetcodes
题意
计算比n小的素数的个数
判断一个数字是否为素数的时间复杂度是 O(n−−√) ,如果直接做,总的时间复杂度就是 O(n1.5) ,这个略慢。
思路
如果n可以在打表的容纳范围内,用素数筛法就可以了!时间复杂度将会降为O(nlog log n),至于为什么是,可以用数学证明的,参考wiki:https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Computational_analysis
代码
/*
问题要求:
计算比n小的素数的个数
判断一个数字是否为素数的时间复杂度是O(sqrt(n)),如果直接做,总的时间复杂度就是O(n^1.5),这个太慢了
*/
class Solution {
public:
// 如果n不是很大的话,就直接用筛法,打表,复杂度为O(nlog n),至于为什么是这样のlater
int countPrimes(int n) {
vector<bool> isPrime(n, true);
int cnt = 0;
for (int i = 2; i < n; ++i) {
if (!isPrime[i])
continue;
++cnt;
for (int j = (i << 1); j < n; j += i)
isPrime[j] = false;
}
return cnt;
}
};

本文介绍了一种高效计算小于n的素数数量的方法。通过使用素数筛法,将时间复杂度从O(n^1.5)降低到O(nloglogn),并提供了具体的C++实现代码。
3万+

被折叠的 条评论
为什么被折叠?



