Nth Prime Number Between A Given Range

 

Write A Program To Display Nth Prime Number Between A Given Ranges ?


Package Programs;
import java.util.Scanner;
public class NThPrimeNumberInRange {
 
 
            public static void main(String[] args) {
                Scanner scanner = new Scanner(System.in);
                System.out.print("Enter the starting number: ");
                int start = scanner.nextInt();
                System.out.print("Enter the ending number: ");
                int end = scanner.nextInt();
                System.out.print("Enter the value of 'n': ");
                int n = scanner.nextInt();
 
                int count = 0;
                int number = start;
                int nthPrime = 0;
 
                while (number <= end) {
                    if (isPrime(number)) {
                        count++;
                        if (count == n) {
                            nthPrime = number;
                            break;
                        }
                    }
                    number++;
                }
 
                if (nthPrime != 0) {
                    System.out.println("The " + n + "th prime number between " + start + " and" + end "is: " + nthPrime);
                } else {
                    System.out.println("No nth prime number found between " + start + " and " + end +".");
                }
            }
 
            public static boolean isPrime(int num) {
                if (num <= 1) {
                    return false;
                }
                // Check from 2 to the square root of the number if there are any divisors.
                for (int i = 2; i * i <= num; i++) {
                    if (num % i == 0) {
                        return false;
                    }
                }
                return true;
            }
        }





Output

Enter the starting number: 10

Enter the ending number: 99

Enter the value of 'n': 6

The 6th prime number between 10 and 99 is: 29

Explanation:

1. We start by importing the java.util.Scanner class, which allows us to take input from the user.

2. We create a static method isPrime() that checks whether a given number num is prime or not. A number is prime if it is greater than 1 and has no divisors other than 1 and itself. We use a for loop to check divisibility from 2 up to the square root of the number because if a number is not divisible by any smaller number up to its square root, it won't be divisible by any larger number either.

3. In the main() method, we create a Scanner object to take input from the user.

4. We prompt the user to enter the lower and upper bounds of the range.

5. We then print all the prime numbers within the given range using a for loop. For each number i in the range, we call the isPrime() method to check if it is prime. If it is, we print the number.

Comments

Popular posts from this blog

Constructor

How To Move Zeros To End Of An Array?

Method Overriding