I am writing a method to find primes up to n(Sieve of Eratosthenes), yes this is for homework. I am looking to improve performance in the method I have written. I have been tweaking this for the last few days but am unable to to follow the pseudocode given and improve performance.
the pseudocode is as follows:
create a queue of numbers to process
fill the queue with integers 2 through n inclusive
create an empty result queue to store primes
repeat the following steps:
obtain the next prime p by removing the first value from the queue of numbers
put p into the result queue of primes
loop through the queue of numbers eliminating all numbers divisible by p
while(p is less than the square root of n)
all remaining values are prime so transfer them to the prime result queue
here is my current method:
public static Queue<Integer> getPrimes(int n) throws IllegalArgumentException
{
if (n<2)
{
throw new IllegalArgumentException();
}
Queue<Integer> integers = new LinkedList<Integer>();
Queue<Integer> primes = new LinkedList<Integer>();
for (int i = 2; i <= n ; i++) {
integers.add(i);
}
boolean[] isMultiple = new boolean[n + 1];
for(int iterate = integers.remove(); iterate <= n; iterate++)
{
if(!isMultiple[iterate])
{
primes.add(iterate);
for(int multiples = iterate * iterate; multiples >= 0 && multiples <= n; multiples += iterate)
{
isMultiple[multiples] = true;
}
}
}
return primes;
}