Perfect number program in PHP
In this post, you will learn how to check for the perfect number using the PHP programming language. The perfect number program is generally asked in PHP coding tests and interviews.
A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. In other words, a number whose sum of factors is equal to the number, excluding the number itself is called a perfect number.
The sum of divisors of a number, excluding the number itself, is called its aliquot sum, so a perfect number is one that is equal to its aliquot sum. For example, 6 has divisors 1, 2 and 3, and 1 + 2 + 3 = 6, so 6 is a perfect number. 6 is the first perfect number.
Perfect Number | Sum of its Divisors |
6 | 1+2+3 |
28 | 1+2+4+7+14 |
496 | 1+2+4+8+16+31+62+124+248 |
8,128 | 1+2+4+8+16+32+64+127+254+508+1,016+2,032+4,064 |
Here, we have mentioned three different ways to find the perfect number in PHP.
Perfect Number Program in PHP using For loop
In the given PHP program, we have checked whether the entered number is perfect or not using the for loop.
<?php
// Perfect Number program in PHP using For Loop
function isPerfectNumber($num)
{
$sum = 0;
// Traversing through each number
for ($i = 1; $i < $num; $i++)
{
if ($num % $i == 0)
{
$sum = $sum + $i;
}
}
//comparing the sum with the number
return $sum == $num;
}
// Driver's code
$num = 28;
if (isPerfectNumber($num))
echo $num." is perfect number.";
else
echo $num." is not a perfect number.";
?>
Output of the above code:
28 is perfect number.
Perfect Number Program in PHP using While loop
In the given PHP program, we have checked whether the entered number is perfect or not using the while loop.
<?php
// Perfect number program in PHP using While Loop
function isPerfectNumber($num)
{
$sum = 0;
$i = 1;
// Traversing through each number
while($i <= $num/2)
{
if($num % $i == 0)
{
//calculating the sum of factors
$sum = $sum + $i;
}
$i++;
}
//comparing the sum with the number
return $sum == $num;
}
// Driver's code
$num = 496;
if (isPerfectNumber($num))
echo $num." is perfect number.";
else
echo $num." is not a perfect number.";
?>
Output of the above code:
496 is perfect number.
Related Articles
PHP reverse a string without predefined functionPHP random quote generator
PHP convert string into an array
PHP remove HTML and PHP tags from string
Import Excel File into MySQL using PHP
PHP array length
Import Excel File into MySQL Database using PHP
PHP String Contains
PHP remove last character from string
PHP calculate percentage of total
PHP sanitize input for MySQL
Display PDF using an AJAX call
How to fetch data from database in php and display in pdf
How to read CSV file in PHP and store in MySQL
How to create a doc file using PHP
PHP SplFileObject Examples
How to Upload a File in PHP
Sending HTML form data to an email address