Duncan's blog

October 10, 2014

Project Euler: problem 34 (PHP) – Digit factorials

Filed under: PHP,Project Euler — duncan @ 8:00 am

34I 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.

Problem 34:

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.

Advertisements

2 Comments »

  1. […] 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 | Reply

  2. […] 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 | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: