March 11, 2024

Java Problem Solution: Check if a Number is Prime or Not in Java


public class PrimeChecker {
    public static void main(String[] args) {
        int numberToCheck = 4; // Change this to test different numbers.
        if (isPrime(numberToCheck)) {
            System.out.println(numberToCheck + " is a prime number.");
        } else {
            System.out.println(numberToCheck + " is not a prime number.");
        }
    }
    // A prime number is a natural number greater than 1 that has no positive divisors
    // other than 1 and itself.
    public static boolean isPrime(int number) {
    	//return true if the number is prime, false otherwise.
    	if (number <= 1) {
            return false; // Numbers less than or equal to 1 are not prime
        }
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false; // If number is divisible by any other number, it's not prime
            }
        }
        return true; // If the loop completes without finding divisors, number is prime
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.