Sieve of Eratosthenes solution
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
方法1: Sieve of Eratosthenes solution
grandyang: https://www.cnblogs.com/grandyang/p/4462810.html
思路:
用hint中的这个算法,穷举所有不为prime,小于n的数字。下面这个算法做了一些优化,都是免去不必要的搜索:
- 从0开始(其实从2开始就可以),遍历至sqrt(n),将所有 i 的整数倍都标记为false。
- if (prime[i]):如果本身自己就不是质数,一定被前面的因数set好了,可以跳过。
- 搜索i的整数倍从 i 倍开始,也就是for (j = i * i, j < n, j += i),前面的搜索是重复的。
最后求一下所有没被set为false的个数。
Complexity
Time Complexity: O(nloglogn), 时间复杂度等于(n/2+n/3+n/5…+n/比n小的最大素数) = n*(小于n的所有素数倒数的和) = O(n * log(logn)), see wiki https://en.wikipedia.org/wiki/Divergence_of_the_sum_of_the_reciprocals_of_the_primes
Space Complexity: O(n)
class Solution {
public:
int countPrimes(int n) {
vector<bool> prime(n, true);
prime[0] = false, prime[1] = false;
for (int i = 0; i < sqrt(n); ++i) {
if (prime[i]) {
for (int j = i*i; j < n; j += i) {
prime[j] = false;
}
}
}
return count(prime.begin(), prime.end(), true);
}
};