Created
January 26, 2019 21:58
-
-
Save RChehowski/63cb6bde3ff469d108043c3c6291d62a to your computer and use it in GitHub Desktop.
Sieve of eratosthenes (java)
This file contains hidden or 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
public static int[] sieveOfEratosthenes(int n) | |
{ | |
final boolean[] map; | |
try { | |
// Math.max(n, 0) is a negative-size protection | |
map = new boolean[Math.max(n, 0)]; | |
} | |
catch (OutOfMemoryError ignore) { | |
return new int[0]; | |
} | |
// 2 is a first prime number | |
final int firstPrime = 2; | |
// 46340 is a Math.sqrt(Integer.MAX_VALUE) to prevent (i * i) overflow | |
final int iMax = 46340; | |
for (int i = 0; i < firstPrime && i < n; i++) { | |
map[i] = true; | |
} | |
// Initialize capacity (with n<2 protection) | |
int cap = Math.max(n - firstPrime, 0); | |
for (int i = firstPrime; (i * i <= n) && i < iMax; i++) { | |
System.out.println("Testing: " + i); | |
// Normalized n is an overflow protection for very big ns | |
final int nn = n - i; | |
for (int j = i * i; j <= nn; j += i) { | |
if (!map[j]) { | |
map[j] = true; | |
--cap; | |
} | |
} | |
} | |
final int[] primes = new int[cap]; | |
for (int i = 0, x = 0; i < n; i++) { | |
if (!map[i]) | |
primes[x++] = i; | |
} | |
return primes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment