Last active
October 26, 2021 23:53
-
-
Save tos-kamiya/0f4c00dec702be035013cc41d4db8b61 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes in Java
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.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