Robson » Little Red Book » Puzzler

Chapter 6 - Question 8

Find all 3-digit numbers that are equal to the sum of the cubes of the digits in the number.

Solution 1

<?
   // loop through all three digit numbers
   for ($n = 111; $n <= 999; $n++)
   {
       // convert to string
       settype($n, 'string');
       // add the cubes together and see if they are the same as the original number
       if (pow($n[0], 3) + pow($n[1], 3) + pow($n[2], 3) == $n)
           // if so, add it to the array
           $narcissistic_numbers[] = $n;
   }
   // show all the numbers that match the rule
   echo implode(', ', $narcissistic_numbers);
?>

Which produces:

153, 370, 371, 407

Log

© 2004-17 robson | cc unless stated