I previously blogged about this Project Euler puzzle nearly 6 years ago, using ColdFusion. This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
Code:
<?php function factorial($x) { $factorial = 1; for ($i = $x; $i > 1; $i--) { $factorial *= $i; } return $factorial; } // calculate the factorials from 0 to 9 $factorials = []; for ($i = 0; $i <= 9; $i++) { $factorials[$i] = factorial($i); } $numbers = []; $total = 0; for ($i = 3; $i <= 99999; $i++) { $sum = 0; // get the factorial of each digit of i for ($j = 0; $j < strlen($i); $j++) { $sum += $factorials[substr($i, $j, 1)]; } // does i = the sum of the factorials? if ($i == $sum) { $numbers[] = $i; } } foreach($numbers as $i) { $total += $i; } echo $total;
I took the same approach as I ended up using with the ColdFusion, where I started out calculating the factorials of all the numbers 0..9, for quick reference later.
[…] which slowed the code right down. However I was able to re-use the factorial function from Problem 34, looping down from $x to 1, instead of doing a foreach loop over the array returned by range(). […]
Pingback by Project Euler: problem 53 (PHP) – Combinatoric selections | Duncan's blog — October 18, 2014 @ 8:05 am |
[…] the approach here from Problem 34, where I first calculated the factorials for the digits […]
Pingback by Project Euler: problem 74 (PHP) – Digit factorial chains | Duncan's blog — October 28, 2014 @ 8:03 am |