Count the number of prime numbers less than a non-negative number, n.
Idea:
Using Sieve of Eratosthenes to get primes in some given range. 时间复杂度 O(n log log n),一篇论文中证明。
Java Code:
// javapublicclassSolution{publicintcountPrimes(intn){if(n <3)return0;boolean[] primes =newboolean[n];Arrays.fill(primes,true); primes[0]= primes[1]=false;for(int i =2; i <=Math.sqrt(n);++i){if(! primes[i]||(i >2&& i %2==0))continue;// if i is not a prime or i is even, continuefor(int x = i * i; x < n; x += i){ primes[x]=false;}}int ret =0;for(boolean isPrime : primes) ret += isPrime ?1:0;// count all 'true' in the arrayreturn ret;}}
class Solution {
public:
int countPrimes(int n) {
vector<int> arr(n);
int ret = 0;
for (int i = 2; i < n; ++i) {
if (arr[i] != 1) {
ret++;
}
int t = i;
while (t < n) {
arr[t] = 1;
t += i;
}
}
return ret;
}
};