Fundamentals pattern (prateek luvs candy )

sir plz once look at my code,one of my test case is not getting absolutely coorect…i m getting a mst lyk,my this code is quiet slow to compute for one test case.

import java.util.Scanner;
public class Main{
static Scanner s=new Scanner(System.in);
public static void main(String args[]) {
int n=s.nextInt();
// if(n>0 && n<=10000) {
int[] arr=new int[n];
for(int j=0;j<n;j++) {
arr[j]=s.nextInt();
}

for(int j=0;j<n;j++) {
	int res=0,  p=2;
 while(arr[j]!=res){
	 int count=0;
	 if(p==2) {
		 res++;
		 p++;
		 continue;
	 }else if(p%2 == 0) {
	        	p++;
	        	continue;
	        }else {
	  boolean flag =true;
			for(int l=3;l<=Math.sqrt(p)+1 ; l+=2) {
				if(p%l == 0) {
					 flag=false;
					p++;
					// break;
				}
			}
			if(flag) {
			res++;
			p++;
			}
		}
 }
		System.out.println(p-1);
		
}

}

}
//}

@sameeksha,

You are supposed to use the prime seive optimisation technique (sieve of eratosthenes). Also make sure that you execute the primeseive function that you will make before the test cases only to prevent TLE.

Precompute the prime numbers using sieve technique.

In the 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.

Precompute all the prime numbers within the constraints and then proceed with the required operation

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.