Description:
Count the number of prime numbers less than a non-negative number, n.
参考https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
class Solution {
public:
int countPrimes(int n) {
if(n<=2)
return 0;
vector<bool> isprime(n,true);
for(int i=3; i*i<n; i=i+2){
if(isprime[i]){
for(int j=i*i; j<n; j+=2*i){ //隔开n个乘积,跳过偶数还有优化
isprime[j] = false;
}
}
}
int count = 1;
for(int i=3; i<n; i+=2){
if(isprime[i]) count++;
}
return count;
}
};