forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountPrimes.java
48 lines (43 loc) · 1.06 KB
/
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
41
42
43
44
45
46
47
48
package math;
import java.util.BitSet;
/**
* Created by gouthamvidyapradhan on 21/03/2017.
Description:
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 = new Double(Math.sqrt(n)).intValue();
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;
}
}