https://leetcode.com/problems/count-primes/description/
Solution 1. Use Sieve of Eratosthenes (13 ms)
int countPrimes(int n) {
if(n<=2) return 0;
bool s[n] = {false}; // faster than vector<bool> s(n,false);
int np = 1;
for(int i=3; i<n; i+=2) {
if(!s[i]) {
np++;
if(i>n/i) continue;
for(int j=i*i, step=i<<1; j<n; j+=step) {
//set step = 2*i to ignore even numbers
s[j] = true;
}
}
}
return np;
}
No comments:
Post a Comment