Robson » Little Red Book » Perfect numbers

Chapter 6 - Question 2

A perfect number is a number whose proper factors sum to itself. For example:

6 has a proper factors of 1, 2 and 3 and 1 + 2 + 3 = 6 so 6 is a perfect number.

Produce a program to find the first three perfect numbers.

Solution 1

<?
   // the amount of perfect numbers to find
   // the 4th perfect number is over 8 thousand, which takes 17 seconds to find on my machine
   // the 5th perfect number is over 3 million, so don't try finding that!
   $perfect_needed = 3;
 
   // start testing at one
   $current = 1;
   // only loop while not enough have been found
   while (count($perfect_numbers) < $perfect_needed)
   {
       // reset the total to zero
       $total = 0;
       // loop from 1 to the current number being tested
       // the number to test up to only needs to be half the current amount        
       for ($n = 1; $n < intval($current / 2)+1; $n++)
       {
           // check if the nested loop counter divides into the current number perfectly
           if ($current % $n == 0)
               // if so, add it to the current total
               $total += $n;
       }
       // if the total is the same amount as the number being tested, it's a perfect number
       if ($total == $current)
           // add it to the array of perfect numbers
           $perfect_numbers[] = $current;
           
       // test the next number
       $current++;
   }    
   // show how many perfect numbers were being found and output them
   echo 'The first ' . $perfect_needed . ' perfect numbers are: ' . implode(', ', $perfect_numbers);
?>

Which produces:

The first 3 perfect numbers are: 6, 28, 496

Log

© 2004-17 robson | cc unless stated