Count Primes
约 1 分钟· 本文阅读 次
本页目录
Count Primes
Count the number of prime numbers less than a non-negative number, n.
Solution
埃拉托斯特尼筛法 (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)
Complexity
时间复杂度 O(nsqrt(n)),空间复杂度 O(1)
Code
public class Solution {
public int countPrimes(int n) {
boolean notPrime[] = new boolean[n + 2];
notPrime[0] = notPrime[1] = true;
for (int i = 2; i * i < n; i++) {
if (!notPrime[i]) {
int c = i * i;
while (c < n) {
notPrime[c] = true;
c += i;
}
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (!notPrime[i])
ans ++;
}
return ans;
}
}相关文章
- 100 Lockers2016-01-16
- Add Digits2016-01-16
- Ants on a Triangle2016-01-16
- The Apocalypse2016-01-16
已恢复到上次阅读位置