Write a Java program to check if the given number is a Prime Number? | StudyEcart | CODE005

 
  import java.util.Scanner;

public class PrimeNumberChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        if (isPrime(number)) {
            System.out.println(number + " is a prime number.");
        } else {
            System.out.println(number + " is not a prime number.");
        }

        scanner.close();
    }

    public static boolean isPrime(int num) {
        if (num <= 1) {
            return false; // Numbers less than or equal to 1 are not prime
        }

        // Check divisibility from 2 to the square root of the number
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false; // If divisible by any number between 2 and sqrt(num), not prime
            }
        }

        return true; // If no divisors found, it's a prime number
    }
}
(code-box)
Explanation:

1. The program starts by importing the `Scanner` class from the `java.util` package, which is used to read user input.

2. In the `main` method, the user is prompted to enter a number.

3. The `isPrime` method is defined to check whether a given number is prime. It takes an integer as a parameter.

4. Inside the `isPrime` method, the first check is whether the number is less than or equal to 1. Prime numbers are greater than 1, so any number less than or equal to 1 is not prime.

5. Next, a loop iterates from 2 to the square root of the number. This is an optimization, as factors of a number are typically found in the range from 2 to the square root of the number.

6. In the loop, the program checks if the number is divisible by the current value of `i`. If it is, then the number is not prime (since a prime number has only two divisors: 1 and itself).

7. If the loop completes without finding any divisors, the program concludes that the number is prime.

8. Back in the `main` method, the `isPrime` function is called with the user's input number. Depending on the return value, the program prints whether the number is prime or not.

9. Finally, the `Scanner` is closed to release the system resources.

This program checks whether the given number is prime by testing its divisibility against numbers from 2 up to the square root of the number. If the number has no divisors within this range, it is considered prime.

🚀 Elevate Your Career with Studyecart! 📚📊

🔥 Get instant job notifications and ace interviews with Studyecart. 📌

Download now

#StudyecartApp #CareerBoost

Post a Comment

0 Comments