1

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;
}
D4RKCIDE
  • 3,439
  • 1
  • 18
  • 34

2 Answers2

3

You can first optimize it in two ways: 1) You do not require integer linkedlist. Instead use a simple for loop.

2) Once you are using for loop, you can first remove all the even numbers as they are obviously divisible by 2. And then just traverse through the odd numbers. Thus decreasing the loop to half.

Code Snippet:

    primes.add(2);
    for(int i=2;i*i<=n;i++)
    {
        isMultiple[2*i]=true;
    }
    for(int i=3;i*i<=n;i+=2)
    {
        if(!isMultiple[i]) 
        {
            primes.add(i);
            for(int j=i*i;j<n;j+=i)
            {
               isMultiple[j]=true;
            }
        }
    }
    return primes;
Rahul Shah
  • 165
  • 2
  • 11
0

As a first small step you can remove the integers queue and replace it with a common for loop:

for (int iterate = 2; iterate < n; iterate++)
{
     if (!isMultiple[iterate]) 
     {
         ...
     }
}
Uli
  • 1,390
  • 1
  • 14
  • 28
  • Yes, unfortunately that is specifically one of the steps I must follow. Originally I had written a method that did not even contain the integers queue. let me add the pseudocode to the original question, that is my fault sorry. – D4RKCIDE Feb 25 '15 at 19:17