Description:
Count the number of prime numbers less than a non-negative number, n.
解题思路:
空间换时间,开一个空间为n的数组,因为非素数至少可以分解为一个素数,因此遇到素数的时候,将其有限倍置为非素数,这样动态遍历+构造下来,没有被设置的就是素数。
public int countPrimes(int n) {
if (n <= 2)
return 0;
boolean[] notPrime = new boolean[n];
int res = 0;
int bound = (int) Math.sqrt(n);
for (int i = 2; i < n; i++) {
if (!notPrime[i]) {
res++;
if (i <= bound)
for (int j = i * i; j < n; j += i)
notPrime[j] = true;
}
}
return res;
}
Java for LeetCode 204 Count Primes
原文:http://www.cnblogs.com/tonyluis/p/4558911.html