-
Notifications
You must be signed in to change notification settings - Fork 819
/
CountPrimes.java
40 lines (37 loc) · 884 Bytes
/
CountPrimes.java
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
33
34
35
36
37
38
39
40
package math;
import java.util.BitSet;
/**
* Created by gouthamvidyapradhan on 21/03/2017. Description:
*
* <p>Count the number of prime numbers less than a non-negative number, n.
*/
public class CountPrimes {
/**
* Main method
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.out.println(new CountPrimes().countPrimes(999187));
}
public int countPrimes(int n) {
if (n == 0 || n == 1 || n == 2) return 0;
else if (n == 3) return 1;
BitSet set = new BitSet();
n = n - 1;
int sqRt = (int) Math.sqrt(n);
int count = n;
for (int i = 2; i <= sqRt; i++) {
if (!set.get(i)) {
for (int j = 2; (i * j) <= n; j++) {
if (!set.get(i * j)) {
count--;
set.set(i * j);
}
}
}
}
return count - 1;
}
}