How to find the nth prime number in Java

In this program, we will find the nth prime number using java. For this, we are importing the Scanner class.

Importing the scanner class:

import java.util.Scanner;

Now we use this scanner class to take the input from the user.

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();

Java program to find the nth prime number

import java.util.Scanner;
public class Prime {
  public static void main(String[] args) {
    int num=1, count=0, i;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a number to find the nth prime number: ");
    int n = sc.nextInt(); 
    while (count < n){
      num=num+1;
      for (i = 2; i <= num; i++){
        if (num % i == 0) {
          break;
        }
      }
      if ( i == num){
        count = count+1;
      }
    }
    System.out.println("Value of nth prime is: " + num);
  }
}

Steps for understanding the program

Let’s see the steps we did to find the nth prime number in Java:

  1. import the Scanner class which is found in java. util package.
  2. Declaring and initializing some variables.
  3. Using the Scanner class to take input from the user.
  4. The logic of the program:
    while (count < n){
    
    num=num+1;
    
    for (i = 2; i <= num; i++){
    
    if (num % i == 0) {
    
    break;
    
    }
    
    }
    
    if ( i == num){
    
    count = count+1;
    
    }
    
    }

Understanding the logic of the program

For understanding the logic of the program you must learn how to find whether the number is prime or not in this article – Java Program To Check A Number Is Prime or Not.

This loop continues until the value of the count is less than n. If the condition is true then it will increase the value of num by 1.
The for loop begins with the initialization of i by 2 till the value is less than or equal to num. Every time when the condition is true it will divide the value of num by i and checks if its equal to zero or not. If it is equal to zero, the loop breaks and checks whether i is equal to num. If it is so then the value of count is increased by 1 and then again checks the condition of while loop.
When the while loop terminates we get our final value in the variable num.

Output:

Enter any number to compute the nth prime number: 5
Value of nth prime: 11

 

Leave a Reply

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