Problem:
Description:
Count the number of prime numbers less than a non-negative number, n
Analysis:
Solutions:
C++:
int countPrimes(int n) {
if(n <= 2)
return 0;
vector<bool> primes(n, true);
int num = n - 2;
int search_bound = int(sqrt(n));
for(int i = 2; i <= search_bound; ++i) {
if(primes[i]) {
for(int j = 2; ; ++j) {
unsigned int product = static_cast<unsigned int>(i) * static_cast<unsigned int>(j);
if(product >= n)
break;
else if(primes[product]) {
primes[product] = false;
--num;
}
}
}
}
return num;
}
Java
:
Python: