Created
March 26, 2015 18:40
-
-
Save pkshultz/87e305c0ab5bbd1fd56d to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
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
// Sieve of Eratosthenes | |
public int sieve_of_eratosthenes(int input) | |
{ | |
boolean [] is_prime = new boolean [input]; | |
int number_of_primes = 0; | |
// Set all values to true | |
Arrays.fill(is_prime, Boolean.TRUE) | |
// Sift | |
for (int i = 2; i <= sqrt(input); i++) | |
{ | |
if (is_prime[i]) | |
{ | |
for (int j = pow(i, 2); j < input; j++) | |
{ | |
if ((j % i) == 0) | |
{ | |
is_prime[j] = false; | |
} | |
} | |
} | |
} | |
// Collect number of primes | |
for (int i = 2; i < input; i++) | |
{ | |
if (is_prime[i]) | |
{ | |
number_of_primes++; | |
System.out.println("%d %n", is_prime[i]); | |
} | |
} | |
return number_of_primes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment