A Prime number is that number which is only divisible by 1 and itself. E.g 5, 7, 11 etc.
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
- Take input the value of (n).
- Run while loop with condition (c != n) where c will store the counts of prime numbers discovered (Initially value of ‘c’ is 0).
- Increment ‘i’ (i++) for next number check (Initially ‘i’ is 1)
- Check if the current number (i) is Prime or not.
- 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
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 | import java.util.Scanner; public class NthPrime { public static void main(String args[]){ Scanner in = new Scanner(System.in); int i=1, n, c =0; //Input the value of 'n' System.out.println("Enter the value of n"); n= in.nextInt(); //While loop should run until we get to the nth prime number i.e (c == n) while(c != n){ i++; if(isPrime(i)) c++; //'c' will get incremented every time when we find a prime number } System.out.println("Nth Prime Number is: "+i); } private static boolean isPrime(int num){ boolean flag = true; //Assuming that 'num' is Prime for(int i=2; i<num; i++){ if(num%i == 0){ //If num is divisible by any number other than 1 and itself then, it is Not Prime. flag = false; //Indicate input is not Prime break; //Since the num is not prime, so no use of iterating further } } return flag; } } |
Output
1 2 3 | Enter the value of n 15 Nth Prime Number is: 47 |
If you have any suggestion then comment below.