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?