Description:
Count the number of prime numbers less than a non-negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
统计小于n的素数个数,直接枚举会超时。这里使用素数筛
class Solution {
public:
int countPrimes(int n) {
int *table = new int[n];
table[2] = 0;
int count = 0;
for( int i = 2; i < n; i++ ) {
if( table[i] == 0 ) {
count++;
for( int j = i * 2; j < n; j += i ) {
table[j] = 1;
}
}
}
return count;
}
};