朴素eratosthenes筛数法
O(nloglogsqrt(n)) time
证明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public: int countPrimes(int n) { if (n < 2) return 0; vector<bool> isPrime(n, true); isPrime[0] = isPrime[1] = false; for (int i = 2; i * i < n; ++i) { if (!isPrime[i]) continue; for (int j = i * i; j < n; j += i) { isPrime[j] = false; } } return count(isPrime.begin(), isPrime.end(), true); } };
|