204. Count Primes
Description:
Count the number of prime numbers less than a non-negative number, n.
解法
Sieve of Eratosthenes
(素数的概念:大于1的数只能被1和本身整除的数。)
2的所有倍数都是false,3的所有倍数都是false,
5的所有倍数都是false,
7的所有倍数都是false,
9的所有倍数都是false
…….
最后剩余的true即为素数。
public class Solution {
public int countPrimes(int n) {
int count = 0;
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) {
continue;
}
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
for (int i = 2; i < n; i++) {
if (isPrime[i]) {
count++;
}
}
return count;
}
}