A Prime number is that number which is only divisible by 1 and itself. E.g 5, 7, 11 etc.

Prime numbers

We have already discussed the Java Program to check whether the input number is prime or not? here we will use the same concept to find the nth prime number in java.

Recommended: Check Prime number in Java

Steps to find nth Prime number in Java

  1. Take input the value of (n).
  2. Run while loop with condition (c != n) where c will store the counts of prime numbers discovered (Initially value of ‘c’ is 0).
  3. Increment ‘i’ (i++) for next number check (Initially ‘i’ is 1)
  4. Check if the current number (i) is Prime or not.
  5. If YES then only increment ‘c’ (c++).

By following the above steps, the while loop will run until c == n (i.e until we find the nth prime number). This means the last value of ‘i’, which is a prime number caused the value of ‘c‘ to get incremented and became equal to ‘n‘ which in turn causes the loop to break. Hence, ‘i’ is the nth prime number.

Find and Print Nth Prime Number in Java


If you have any suggestion then comment below.

Leave a Reply

Close Menu