Skip to content

Instantly share code, notes, and snippets.

@jinahya
Last active April 28, 2019 04:32
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 jinahya/9a66c0d714a14d3e01a214460cccb670 to your computer and use it in GitHub Desktop.
Save jinahya/9a66c0d714a14d3e01a214460cccb670 to your computer and use it in GitHub Desktop.
The Sieve of Eratosthenes in Java
import java.util.List;
import static java.util.stream.Collectors.toList;
import java.util.stream.IntStream;
import static java.util.stream.IntStream.rangeClosed;
public class SieveOfEratosthenes {
static boolean isPrime(final int candidate) {
if (candidate < 2) {
return false;
}
final int sqrt = (int) Math.sqrt(candidate);
for (int i = 2; i <= sqrt; i++) {
if (candidate % i == 0) {
return false;
}
}
return true;
}
static int nextPrime(final int previous) {
if (previous < 2) {
return 2;
}
for (int candidate = previous + 1; candidate > 0; candidate++) {
if (isPrime(candidate)) {
return candidate;
}
}
throw new RuntimeException("failed to get a prime number greater than " + previous);
}
public static void main(final String[] args) {
if (args.length == 0) {
return;
}
final int max = Integer.parseInt(args[0]);
if (max < 2) {
return;
}
final List<Integer> candidates = rangeClosed(2, max).boxed().collect(toList());
for (int current = 2; true; ) {
final int prime = current;
if (prime > candidates.get(candidates.size() - 1)) {
break;
}
candidates.removeIf(n -> n > prime && n % prime == 0);
try {
current = nextPrime(current);
} catch (final RuntimeException re) {
break;
}
}
for (int n : candidates) {
if (!isPrime(n)) {
System.out.println("not a prime numer: " + n);
}
}
System.out.println(candidates);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment