Created
April 26, 2016 16:38
-
-
Save nielsutrecht/8d9ac6089daf287601c31c18b4de9fd0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.BitSet; | |
public class EratosthenesSieve { | |
private BitSet primes = null; | |
public void init(int maxNum) { | |
final long start = System.currentTimeMillis(); | |
primes = new BitSet(maxNum+1); | |
primes.clear(0, 1); | |
primes.set(2, maxNum, true); | |
for (int i = 2; i < maxNum; i++) { | |
if (primes.get(i)) { | |
int mul = 2; | |
while (mul * i > 0 && mul * i <= maxNum) { | |
primes.set(i * mul, false); | |
mul++; | |
} | |
} | |
} | |
final long duration = System.currentTimeMillis() - start; | |
System.out.println(String.format("Generated primes up to %s in %s ms.", maxNum, duration)); | |
} | |
public boolean isPrime(int num) { | |
return primes.get(num); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment