PHP program to check whether a given number is prime or not:
<?php
function isPrime($number) {
if ($number < 2) {
return false;
}
for ($i = 2; $i <= sqrt($number); $i++) {
if ($number % $i == 0) {
return false;
}
}
return true;
}
$number = 17; // The number to check for primality
if (isPrime($number)) {
echo $number . " is a prime number.";
} else {
echo $number . " is not a prime number.";
}
?>
In this program, the isPrime()
function takes an input number and checks if it is a prime number. The function first checks if the number is less than 2, as prime numbers are greater than or equal to 2. If the number is less than 2, it immediately returns false
.
Next, the function iterates from 2 to the square root of the given number, checking if any of these numbers divide the given number evenly (i.e., without leaving a remainder). If any such divisor is found, the number is not prime, and the function returns false
. Otherwise, if no divisors are found, the number is considered prime, and the function returns true
.
In the main part of the program, a test case is provided where the number 17
is checked for primality using the isPrime()
function. The program then outputs the result accordingly.
You can change the value of the $number
variable to test for primality of different numbers.