Prime visits : how to modify this code as i am facing time limit error

import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [][] arr = new int [n][2];
for(int i =0;i<n ;i++)
{
arr[i][0] = sc.nextInt();
arr[i][1] = sc.nextInt();
}
for(int k = 0 ; k < n ; k++)
{
int count = 0 , counter = 0;
if(arr[k][0]==1||arr[k][0]==2)
{ arr[k][0]=3 ;
count = 1;}
else
{ count = 0;}
for(int i = arr[k][0] ; i<= arr[k][1] ;i++)
{ counter = 0;
for(int j =2 ; j*j<=i ; j++)
{
if(i%j==0)
{counter = 1;
break;}
}
if(counter == 0)
{ count ++;}
}
System.out.println(count);
}
}
}

Hi @mananaroramail,

The approach you are using will give you TLE for sure.

To deal with TLE here you need to use Sieve technique where you create a boolean array of b+1 size. And start from the first prime number i.e. 2.

Take its square(4) and increment it by the number you took (i.e. 4,6,8,10 and so on).

Mark all these as false since they cannot be primes. Now take the next unmarked number, 3.

And mark 9,12,15 and so as false. Similarly do it for 4. 16,20,24 and so on as false.

When you finish the loop, count all the positions marked as true between a and b. This will be our final answer.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.