TimeLimited error

Sir/Mam,
I tried all methods of solving this question which is basically Finding the nth prime number, but still, I got the time-limited error of 6.02sec. Even though I tried the method of prime Sieve or Root n method. Please help.

Hi Sanchit,
Can you please share your code that you are submitting?

import java.util.; public class Main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(); int counter=0; int j; for(j=2;counter!=n;j++) if(isprime(j)) counter++; System.out.println(–j); } sc.close(); } private static boolean isprime(int n) { if(n==1) return false; for(int i=2;ii<=n;i++) { if(n%i==0) return false; } return true; } }

import java.util.; public class Main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(); int counter=0; int j; for(j=2;counter!=n;j++) if(isprime(j)) counter++; System.out.println(–j); } sc.close(); } private static boolean isprime(int n) { if(n==1) return false; for(int i=2;ii<=n;i++) { if(n%i==0) return false; } return true; } }

Hi @Sanchit1998,

I responded to you on personal chat on 12th October itself.

Anyway, Since you are using the i*i<=n, this approach will give you a TLE. Use the sieve technique.

To deal with TLE 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. 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.