Skip to content

Instantly share code, notes, and snippets.

@xpcoffee
Created December 7, 2014 15:38
Show Gist options
  • Save xpcoffee/758ee6a69120d81d2de3 to your computer and use it in GitHub Desktop.
Save xpcoffee/758ee6a69120d81d2de3 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
import java.util.LinkedList;
public class SieveOfEratosthenes
{
private static final boolean PRIME = false;
private static final boolean COMPOSITE = true;
private boolean[] array;
private int index;
/*
* PUBLIC
*/
/* constructor */
public SieveOfEratosthenes(int upper_bound)
{
array = new boolean[upper_bound + 1];
sieve();
}
/* returns ascending list of primes */
public LinkedList<Integer> ascending()
{
LinkedList<Integer> list = new LinkedList<Integer>();
for(Integer i = 0; i < array.length; i++) {
if(!array[i])
list.add(i);
}
return list;
}
/* returns descending list of primes */
public LinkedList<Integer> descending()
{
LinkedList<Integer> list = new LinkedList<Integer>();
for(Integer i = array.length - 1; i >= 0; i--) {
if(!array[i])
list.add(i);
}
return list;
}
/* tester function */
public static void main(String[] args)
{
/* input */
int upper_bound = 100;
long tic, toc;
if(args.length != 0)
upper_bound = Integer.parseInt(args[0]);
/* sieve */
tic = System.nanoTime();
SieveOfEratosthenes prime_sieve = new SieveOfEratosthenes(upper_bound);
int num_primes = prime_sieve.ascending().size();
toc = System.nanoTime();
/* elapsed time */
String elapsed = "";
double time = 1.0 * (toc - tic) / 1E9;
if(time > 1E-3) elapsed = Double.toString(time) + " sec.";
else if(time > 1E-6) elapsed = Double.toString(time * 1E3) + " millisec.";
/* output */
System.out.println("Number of primes less than " + upper_bound + ": " + num_primes);
System.out.println("Approx. elapsed time: " + elapsed);
}
/*
* PRIVATE
*/
/* applies sieve */
private void sieve()
{
index = 2;
crossOutMultiples(index);
while(nextPrime())
crossOutMultiples(index);
}
/* crosses out all multiples of a given prime */
private void crossOutMultiples(int prime)
{
int i = 2 * prime;
while(i < array.length) {
array[i] = COMPOSITE;
i += prime;
}
}
/* returns next prime (ascending) */
private boolean nextPrime()
{
do {
index++;
if(index > (array.length - 1))
return false;
} while(array[index] == COMPOSITE);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment