Skip to content

Instantly share code, notes, and snippets.

@nielsutrecht
Created April 26, 2016 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nielsutrecht/8d9ac6089daf287601c31c18b4de9fd0 to your computer and use it in GitHub Desktop.
Save nielsutrecht/8d9ac6089daf287601c31c18b4de9fd0 to your computer and use it in GitHub Desktop.
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