RUN TIME ERROR!

in assignment question PRATEEK LOVES CANDY, i m getting run time error please provide me an alternate solution
MY CODE!!

Scanner scn= new Scanner (System.in);
int T =scn.nextInt();
while(T–>0) {
int val =scn.nextInt();
int ans=0;
int N =2;
int num=0;
while(val!=0){
//Scanner scn = new Scanner(System.in);

	int div =2;
	boolean flag =false;
	if(N==1 || N==0) {
		flag=true;
	}
	while(div<=N-1) {
		if(N%div==0) {
			flag=true;
		}
		div =div+1;
		}
		
	    if(flag==false) {
	    	val=val-1;
	    	ans=ans+1;
	    	num =N;
	    }
	  N++;  }
	System.out.println(num);
	
	    	//else {

// System.out.println(“Not-prime”);
// }

}

@Laibaqureshi227 wait giving you the correct approach!

okiee
also tell me where i m wrong

@Laibaqureshi227 Your code is giving time limit exceeded. The reason is that constraints are very high. And for every computation of test cases you are doing same work of finding primes.

So you can do two changes:

  • Precompute or store primes upto test cases once and query them for each test case.
  • Using sieve of eratosthenes, read about it if you don’t know.

Here I am attaching code for ya reference,


If ya doubt is clear, mark it resolved and rate!
Happy coding!

ok then tell me how i should decide to take size of array

@Laibaqureshi227 i have posted my code above, refer it please!