Doubt regarding Prateek loves Candy problem

I have used Sieve of Eratosthenes technique , but still i am getting Time Limit Exceeded problem . Can you tell me how to get rid of this problem .
This is my code :

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in) ;
int n = scan.nextInt() ;

	while(n-- > 0){
		int p = scan.nextInt() ;
		int ans = 0 ; int count = 0 ;
		boolean[] arr = new boolean[1000000] ;
		ArrayList<Integer> al = new ArrayList<Integer>() ;
		
		for(int i = 0 ; i < arr.length ; i++ )
		  arr[i] = true ;

		arr[0] = false ; arr[1] = false ;

		for(int i = 2 ; i <= Math.sqrt(1000000) ; i ++){

			if(arr[i] == true){
				
				for(int j = i*i ; j < arr.length ; j+= i){
					arr[j] = false ;
				}
			}
		}
		
		for(int i = 2 ; i < arr.length ; i ++){
			if(arr[i] == true){
				al.add(i) ;
			}
		}
		
		System.out.println(al.get(p-1)) ;
	}
}

}

@Lalit2142,
If you are using sieve, the main objective is to store all prime numbers in the given range of constraints. You are doing sieve for every query of the question which causes the TLE.

https://ide.codingblocks.com/s/197138 I have corrected your code. I have made a method which returns an arraylist of all the prime numbers (you can even do it without the arraylist).

Kindly understand the code and mark the doubt as resolved, if your query is resolved.

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.