Skip to content

Instantly share code, notes, and snippets.

@tos-kamiya
Last active October 26, 2021 23:53
Show Gist options
  • Save tos-kamiya/0f4c00dec702be035013cc41d4db8b61 to your computer and use it in GitHub Desktop.
Save tos-kamiya/0f4c00dec702be035013cc41d4db8b61 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes in Java
import java.util.Arrays;
import java.util.stream.IntStream;
class Main {
public static int[] simpleSieve(int limit) {
boolean[] isPrime = new boolean[limit + 1];
Arrays.fill(isPrime, true);
for (int n = 2; n <= limit; n++) {
if (isPrime[n]) {
for (int m = n * n; m <= limit; m += n) {
isPrime[m] = false;
}
}
}
return IntStream.rangeClosed(2, limit).filter(n -> isPrime[n]).toArray();
}
public static void main(String[] args) {
int[] primes = simpleSieve(100);
System.out.println(Arrays.toString(primes));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment