Duncan's blog

October 9, 2014

Project Euler: problem 30 (PHP) – Digit fifth powers

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

30I previously blogged about this Project Euler puzzle nearly 6 years ago, using Python.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Problem 30:

Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44

As 1 = 14 is not a sum it is not included.

The sum of these numbers is 1634 + 8208 + 9474 = 19316.

Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.

Code:

<?php
$powers = [];
$grandtotal = 0;

foreach (range(2, 354294) as $i) {
	$total = 0;

	for ($j = 0; $j < strlen($i); $j++) {
		$total += pow(substr($i, $j, 1), 5);
	}
	
	if ($total == $i) {
		$powers[] = $i;
	}		
}

foreach ($powers as $i) {
	$grandtotal += $i;
}

echo $grandtotal;

Nothing too fancy, very similar to my Python approach.

Leave a Comment »

No comments yet.

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

Blog at WordPress.com.

%d bloggers like this: