I try to minimize the loop . It accepts all the testcases till 10^7.
when I tried with testcase
1
10^7
10^9
it throwing the error
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at PrimeSeive.primeSeive(Main.java:32)
at PrimeSeive.main(Main.java:20)
here is my code. kindly check whether my logic is correct or not.
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class PrimeSeive {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
Integer total=in.nextInt();
while(total > 0){
Integer firstNo=in.nextInt();
Integer lastNo=in.nextInt();
List<Integer> primeNo=primeSeive(firstNo,lastNo);
for(int i=0;i<primeNo.size();i++){
System.out.println(primeNo.get(i));
}
total--;
}
}
private static List<Integer> primeSeive(Integer firstNo, Integer lastNo) {
Integer num[]=new Integer[(lastNo/2)];
List<Integer> result=new ArrayList<Integer>();
if(firstNo==1)
firstNo++;
for(int i=0,j=firstNo;j<=lastNo;j++){
if(j%2!=0){
num[i]=j;
i++;
}
}
for(int i=3;i<=Math.sqrt(lastNo)+1;i=i+2){
int j=i+i;
int k=0;
while((j<=lastNo)&&(k<num.length)&&(num[k]!=null)){
if(num[k]==j){
num[k]=1;
k++;
j=j+i;
}
else if(num[k]<j){
k++;
}
else if(num[k]>j){
j=j+i;
}
}
}
for(int i=0;((i<num.length)&&(num[i]!=null));i++){
if(num[i]!=1){
result.add(num[i]);
}
}
return result;
}
}