I’ve worked upon a code for Sieve of Eratosthenes in Java, but I face a few time and space efficiency issues.
Here’s the code :
import java.util.*;
class EratosthenesSeive
{
public static void main(String args[])
{
ArrayList<Long> myPrimeList = new ArrayList<Long>();
ArrayList<Long> myTempPrimeList = new ArrayList<Long>();
ArrayList<Boolean> isPrimeNumber = new ArrayList<Boolean>();
int index = 0;
long ul = 1500l;
long ll = 2;
do
{
myTempPrimeList.add(ll);
isPrimeNumber.add(true);
ll++;
}while( ll != (ul+1));
for(long i : myTempPrimeList)
{
if(isPrimeNumber.get(index))
{
myPrimeList.add(i);
for(long j = i ; j*i <= ul; j++)
{
isPrimeNumber.set(myTempPrimeList.indexOf(j*i),false);
}
}
index++;
}
System.out.println(myPrimeList);
}
}
It seems to be working fine for input upto 10^3, at 10^4 it simply hangs and at 10^5 and above I get OutOfMemoryError.
And the code seems to be working alright, but I would like to fasten it up a bit more. Any suggestions?
One possible optimization would be replacing the ArrayLists with arrays of primitive types, given that you know beforehand the size of the arrays needed. This will have the effect of preventing all the unnecessary boxing/unboxing of values currently present in your code.
Also, be aware that you don’t have to store even numbers in the array, only odd numbers – doing so will reduce the memory requirements and processing time by half.
For solving the OutOfMemoryError you can fiddle with the JVM’s configuration parameters at startup, making available more heap space for the application.