Prime Visits JAVA without arrays

My code is unable to clear test case 2 due to TLE. Can you make improvements to this code? Or do we have to dedicatedly use arrays only?

import java.util.*;
public class Main {
public static void main(String args[]) {

	Scanner scn = new Scanner(System.in);
	int tc = scn.nextInt();
	while(tc-->0){
		int n = scn.nextInt();
		int m = scn.nextInt();
		int count = 0;
		for(int i = n;i<=m;i++){
			for(int p = 2;p<=i;p++){
				if(i%p==0){
					if(p!=i){
					break;
					}
				else{
					count++;
				}
				}
			}
		}
		System.out.println(count);
	}
	

}

}

Hey @Raunak-Agrawal-1537545869717573
here’s my suggestion to you. While doing these kinds of questions try to minimize the redundant operations.

Here it is calculating primes.
Think if T is like 10^4 and n is 10^6 and in worst case each of the test cases has very large value so you will be computing primes again and again and that will give you a TLE.

So precompute the primes once upto the given constraints, you will be good to go
And also find prime number in sqt(N) time