Count Primes
Count the number of prime numbers less than a non-negative number, n.
class Solution {
public:
int countPrimes(int n) {
vector<bool> isPrime(n, true);
for(int i = 4; i < n; i+=2){isPrime[i] = false;} // 0, 1 are not prime well
for(int i = 2; i <= sqrt(n); i++){
if(isPrime[i]){
for(int j = i*i; j < n; j+=(i<<1)){
isPrime[j] = false;
}
}
}
int cnt = 0;
for(int i = 2; i < n; i++){
if(isPrime[i]){
cnt++;
}
} return cnt;
}
};
筛法求素数