-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSieve.java
40 lines (38 loc) · 1005 Bytes
/
Sieve.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 sieve;
import java.util.BitSet;
/**
* This program runs the Sieve of Erathostenes benchmark. It computes all primes up to 2,000,000.
*
* @author Cay Horstmann
* @version 1.21 2004-08-03
*/
public class Sieve {
public static void main(String[] args) {
int n = 2000000;
long start = System.currentTimeMillis();
BitSet b = new BitSet(n + 1);
int count = 0;
int i;
for (i = 2; i <= n; i++)
b.set(i);
i = 2;
while (i * i <= n) {
if (b.get(i)) {
count++;
int k = 2 * i;
while (k <= n) {
b.clear(k);
k += i;
}
}
i++;
}
while (i <= n) {
if (b.get(i)) count++;
i++;
}
long end = System.currentTimeMillis();
System.out.println(count + " primes");
System.out.println((end - start) + " milliseconds");
}
}