LeetCode - Count Primes
Problem description
Count the number of prime numbers less than a non-negative number, n.
Example:
1
2
3
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Analysis
This is a easy problem. There are two things need to be careful about.
The first is that we can iterate all i where i * i < n, which make the size of run into sqrt size.
And the second one is to use Sieve to calculate the prime quickly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public int countPrimes(int n) {
if (n <= 2){
return 0;
}
boolean[] hole = new boolean[n];
hole[0] = true;
hole[1] = true;
hole[2] = false;
for (int i = 2; i*i < n; i++){
if (!hole[i]){
int max = n % i == 0 ? n/i:n/i+1;
for (int j = 2; j < max; j++){
hole[j*i] = true;
}
}
}
int cnt = 0;
for (int i = 0; i < n; i++){
if (!hole[i]){
cnt++;
}
}
return cnt;
}
}
A more elegant code is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static int countPrimes(int n){
boolean primes[] = new boolean[n];
for(int i=0; i<primes.length;i++){
primes[i] = true;
}
for(int i=2; i*i <primes.length;i++){
if(primes[i]){
for(int j=i;j*i<primes.length;j++){
primes[i*j]=false;
}
}
}
int primesCount =0;
for(int i=2;i<primes.length;i++){
if(primes[i]){
primesCount++;
}
}
return primesCount;
}