Algorithm to check if a number if a perfect number

前端 未结 4 2152
走了就别回头了
走了就别回头了 2021-01-05 08:04

I am looking for an algorithm to find if a given number is a perfect number.

The most simple that comes to my mind is :

  1. Find all the factors of the nu
4条回答
  •  执念已碎
    2021-01-05 08:40

    Here's a quick algorithm just for fun, in PHP - using just a simple for loop. You can easliy port that to other languages:

    function isPerfectNumber($num) {
            $out = false;
    
            if($num%2 == 0) {
                $divisors = array(1);
                for($i=2; $i<$num; $i++) {
                    if($num%$i == 0)
                        $divisors[] = $i;
                }
    
                if(array_sum($divisors) == $num)
                    $out = true;
            }
    
            return $out ? 'It\'s perfect!' : 'Not a perfect number.';
        }
    

    Hope this helps, not sure if this is what you're looking for.

提交回复
热议问题