Check if a number is perfect, abundant, or deficient PHP Program

In number theory, a number is classified as perfect, abundant, or deficient based on the sum of its proper divisors (excluding itself):

1. Perfect: The sum of proper divisors equals the number.
– Example: 6 (1 + 2 + 3 = 6)
2. Abundant: The sum of proper divisors is greater than the number.
– Example: 12 (1 + 2 + 3 + 4 + 6 = 16 > 12)
3. Deficient: The sum of proper divisors is less than the number.
– Example: 8 (1 + 2 + 4 = 7 < 8)

Here’s how you can implement this in PHP:

<?php
function classifyNumber($number) {
if ($number <= 0) {
return "Invalid input. Please provide a positive integer.";
}
$sumOfDivisors = 0;

// Find proper divisors and sum them
for ($i = 1; $i <= $number / 2; $i++) {
if ($number % $i === 0) {
$sumOfDivisors += $i;
}
}

// Classify the number
if ($sumOfDivisors === $number) {
return "$number is a perfect number.";
} elseif ($sumOfDivisors > $number) {
return "$number is an abundant number.";
} else {
return "$number is a deficient number.";
}
}

// Test the function
echo classifyNumber(6) . "\n"; // Perfect
echo classifyNumber(12) . "\n"; // Abundant
echo classifyNumber(8) . "\n"; // Deficient
echo classifyNumber(28) . "\n"; // Perfect
echo classifyNumber(0) . "\n"; // Invalid input
?>

Output:

6 is a perfect number.
12 is an abundant number.
8 is a deficient number.
28 is a perfect number.

Invalid input. Please provide a positive integer.

Explanation:

1. The function `classifyNumber` calculates the sum of proper divisors of the input number.
2. It then compares the sum to the original number to determine if it’s perfect, abundant, or deficient.
3. The function also handles invalid inputs (e.g., non-positive numbers).

You can test this function with any positive integer to classify it.