Skip to content

Instantly share code, notes, and snippets.

@pkshultz
Created March 26, 2015 18:40
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 pkshultz/87e305c0ab5bbd1fd56d to your computer and use it in GitHub Desktop.
Save pkshultz/87e305c0ab5bbd1fd56d to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
// 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