Question
Count the number of prime numbers less than a non-negative number, n.
Solution 1
Naive way, to check each number one by one. If a number i is prime, then for x from o to (i - 1), i % x != 0. Time complexity O(n^2).
Solution 2
Sieve of Eratosthenes 算法:
由于一个合数总是可以分解成若干个质数的乘积,那么如果把质数(最初只知道2是质数)的倍数都去掉,那么剩下的就是质数了。
例如要查找100以内的质数,首先2是质数,把2的倍数去掉;此时3没有被去掉,可认为是质数,所以把3的倍数去掉;再到5,再到7,7之后呢,因为8,9,10刚才都被去掉了,而100以内的任意合数肯定都有一个因子小于10(100的开方),所以,去掉,2,3,5,7的倍数后剩下的都是质数了。
public class Solution {
public int countPrimes(int n) {
if (n <= 2)
return 0;
boolean[] primes = new boolean[n];
primes[0] = false;
for (int i = 2; i < n; i++) primes[i] = true;
for (int i = 2; i < Math.sqrt(n); i++) {
if (primes[i] == true) {
int j = 2;
while (i * j < n) {
primes[i * j] = false;
j++;
}
}
}
int result = 0;
for (int i = 2; i < n; i++) {
if (primes[i])
result++;
}
return result;
}
}