<?php
function isPerfectNumber($number) {
$sum = 1;
for ($i = 2; $i <= sqrt($number); $i++) {
if ($number % $i === 0) {
$sum += $i;
// If the divisors are equal, only count once (e.g., for perfect squares)
if ($i !== $number / $i) {
$sum += $number / $i;
}
}
}
return $sum === $number;
}
$testNumber = 28;
if (isPerfectNumber($testNumber)) {
echo "$testNumber is a perfect number.";
} else {
echo "$testNumber is not a perfect number.";
}
?>
- The script defines a function
isPerfectNumber
that checks whether a given number is a perfect number. - A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself).
- The function iterates through divisors up to the square root of the number, adding them to the sum.
- The script then calls the function with a sample number (
$testNumber
) and prints the result.