In this post, we will see how to find nth Prime number in java.
Table of Contents
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.
- Increment
- Return
i
which is nth prime number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
package org.arpit.java2blog; import java.util.Scanner; public class NthPrimeNumberJava { public static void main(String args[]){ Scanner in = new Scanner(System.in); //Input the value of 'n' System.out.println("Enter the value of n"); int n= in.nextInt(); int nthPrimeNumber = findNthPrimeNumber(n); System.out.println("Nth Prime Number is: "+nthPrimeNumber); } private static int findNthPrimeNumber(int n) { if(n==1) { return 2; } int i=1; int count=1; //While loop should run until we find nth prime number i.e (count != n) while(count != n){ // increment number by 2 as even numbers are always not prime i+=2; if(isPrime(i)) count++; // increment the count when we get prime number } // return nth prime number return i; } public static boolean isPrime(int num) { if (num <= 1) { return false; } for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return false; } } return true; } } |
Output:
Enter the value of n
24
Nth Prime Number is: 89
24
Nth Prime Number is: 89
That’s all about how to find nth prime number in java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.