您的位置:首页 > 其它

204. Count Primes

2016-04-18 15:47 330 查看
除了C语言课本里方法,另一种求质数的算法:

https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

给出的参考代码:

public int countPrimes(int n) {
boolean[] isPrime = new boolean
;
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}
return count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: