204. Count Primes
Given an integer n, return the number of prime numbers that are strictly less than n.
Example 1:
Example 2:
Example 3:
Constraints:
0 <= n <= 5 * 106
Solution:
class Solution {
public int countPrimes(int n) {
boolean[] isPrime = new boolean[n];
Arrays.fill(isPrime, true);
for (int i = 2; i * i < n; i++){
if (isPrime[i]){
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;
}
}