Prime Numbers In Range


Write A Program To Display All Prime Numbers Between Given Ranges ?


Package Programs; import java.util.Scanner; public class PrimeNumbersInRange {
         public static void main(String[] args)             {                 Scanner scanner = new Scanner(System.in);                 System.out.print("Enter thestarting number: ");                 int start = scanner.nextInt();                 System.out.print("Enter theending number: ");                 int end = scanner.nextInt();                 System.out.println("Primenumbers between " + start + " and " + end + ":");                 for (int i = start; i <= end; i++)                 {                     if (isPrime(i))                     {                         System.out.print(i + ", ");                     }                 }             }             public static boolean isPrime(int num)             {                 if (num <= 1)                 {                     return false;                 }                 // Check from 2 to the square root ofthe 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: 20

Enter the ending number: 151

Prime numbers between 20 and 151:

23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,



Explanation:

1. We start by importing the Scanner class to read input from the user.

2. The main method is the entry point of the program. It prompts the user to enter the starting and ending range.

3. The program then calls the printPrimeNumbersInRange method with the entered start and end values.

4. The printPrimeNumbersInRange method takes the start and end values and iterates through each number in the range.

5. For each number in the range, it calls the isPrime method to check if the number is prime.

6. The isPrime method checks if the number is less than or equal to 1, in which case it returns false because prime numbers are greater than 1.

7. For numbers greater than 1, it uses a loop to check if the number is divisible by any number from 2 up to the square root of the number. If it is divisible, the method returns false, indicating the number is not prime. Otherwise, it returns true.

8. The printPrimeNumbersInRange method prints the number if it is prime, and then continues the loop until it reaches the end of the range.

9. Finally, the program displays all the prime numbers found between the given ranges.

Comments

Popular posts from this blog

Constructor

How To Move Zeros To End Of An Array?

Method Overriding