Thursday, October 16, 2025
HomeLanguagesPHP | Check if a number is Perfect number

PHP | Check if a number is Perfect number

A perfect number is a number if it is equal to the sum of its factors,that is original number is equal to sum of all its factors excluding the number itself. We have already discuss how to check if a number is perfect or not in this article. In this article we will discuss about how to do the same in PHP.

Examples:

Input : 6
Output : Perfect Number
Explanation: factors of 6 are 1, 2, 3, 6
             sum of its factors (excluding the 
             number itself) = 1 + 2 + 3 = 6 

Input : 24
Output : Not Perfect Number
Explanation : factors of 24 are 1,2,3,4,6,8,12,24 
              sum of its factors(excluding the 
              number itself) = 1 + 2 + 3 + 4  
                                + 6 + 8 + 12 = 36

The idea to this is we will traverse through each number in the range [1,N) and check if it is a factor of the given number N. If it is a factor, we will add this number to a variable $sum. At the end is the variable $sum is equal to the original number then the given number is a Perfect Number.

Below is the implementation of above idea in PHP:




<?php
// Function to check if a number is perfect
function isPerfectNumber($N)
{
    // To store the sum
    $sum = 0;
       
    // Traversing through each number
    // In the range [1,N)
    for ($i = 1; $i < $N; $i++)
    {
        if ($N % $i == 0)
        {
            $sum = $sum + $i;
        }      
    }
      
    // returns True is sum is equal
    // to the original number.
    return $sum == $N;
}
   
// Driver's code
$N = 6;
  
if (isPerfectNumber($N))
    echo " Perfect Number";
else
    echo "Not  Perfect Number";
?>


Output:

Perfect Number
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS