Find nth prime number in java

In this post, we will see how to find nth Prime number in java.

What is prime number

Prime number is a number that is greater than 1 and divided by 1 or itself.
For example: 5, 7, 13, 23

We have already seen how to check if number is prime or not. We will use same method to find nth prime number in java.

Nth prime number in java

Here are steps to find nth prime number in java.

  • Take value of n from user using Scanner class.
  • Intialize a variable count. It will keep track of number of prime number processed so far.
  • Intialize a variable i. It will keep track of current number.
  • Iterate over while loop until count ! = n
    • Increment i by 2 as even numbers are not prime
    • Check if number is prime. If number is prime then increment count by 1.
  • Return i which is nth prime number.

Output:

Enter the value of n
24
Nth Prime Number is: 89

That’s all about how to find nth prime number in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *