Java Program for nth Prime Number

Java Programs

Summary: In this programming example, we will learn to print the nth prime number using the Java language.

A Prime number is a number that is only divisible by 1 and itself. For example: 5, 7, 11, etc.

Prime numbers

To print the nth prime number, we keep searching for the next prime number starting from 1 until we reach the nth prime number.

For this, we keep counting the prime numbers and when we reach the nth prime number, we output the same.

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;
 
        System.out.print("Enter the value of n: ");
        n= in.nextInt();
 
        //While loop should run until we get to the nth prime number
        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; 
        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;
                break;
            }
        }
        return flag;
    }
}

Output:

Enter the value of n: 15
Nth Prime Number is: 47

In this Java program, we ask the user to input the value of n.

After the user enters n, using while loop we search the next prime number until c=n.

The variable c in the above program is keeping the count of the prime numbers found till then.

One thought on “Java Program for nth Prime Number”

Leave a Reply

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