Write a Java program that checks whether a given number is a prime number or not.
What is a Prime Number?
A prime number is a number greater than 1 that has no divisors other than 1 and itself.
For example: 2, 3, 5, 7, 11, 13, …
class Main {
public static void main(String[] args) {
int num = 41; // Number to check if it's prime
boolean isPrime = true;
// If the number is less than or equal to 1, it's not prime
if (num <= 1) {
isPrime = false;
} else {
// Check divisibility from 2 to the square root of the number
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break; // No need to check further if a divisor is found
}
}
}
// Output the result
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}
Input Initialization:
The number to check for primality is stored in num (41 in this example).
A boolean variable isPrime is initialized to true. This assumes the number is prime unless proven otherwise.
Quick Check for Non-Primes:
If the number is 1 or less, it’s not a prime number, and isPrime is set to false.
Quick Check for Non-Primes:
If the number is 1 or less, it’s not a prime number, and isPrime is set to false.
Result Output:
After the loop, the value of isPrime determines whether num is prime:
If isPrime is true, the program prints that num is a prime number.
Otherwise, it prints that num is not a prime number.
Example Execution
Input: num = 41
num is greater than 1, so the program proceeds to the loop.
The loop checks divisibility for i = 2 to sqrt(41) (~6.4).
41 % 2 != 0
41 % 3 != 0
41 % 4 != 0
41 % 5 != 0
41 % 6 != 0
Since no divisors are found, isPrime remains true.
Output:
41 is a prime number.