学到一种新的方法Sieve of Eratosthenes,非常surprise,
leetcode上面已经把这个算法说的很清楚了,不过感觉算时间
复杂度还是有点复杂的,O(NLOGLOGN)
链接:https://leetcode.com/problems/count-primes/?tab=Description
class Solution {
public:
int countPrimes(int n) {
vector<bool> table(n, true);
for (int i = 2; i * i <= n; i++) {
if (table[i - 1]) {
int p = i * i;
while (p < n) {
table[p - 1] = false;
p += i;
}
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (table[i - 1]) {
count++;
}
}
return count;
}
};