Duncan's blog

October 20, 2014

Project Euler problem 56 (PHP) – Powerful digit sum

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

NumbersI previously blogged about this Project Euler puzzle over 5 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 56:

A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.

Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum?


$maxsum = 0;
$limit = 99;

foreach (range(1, $limit) as $base) {
    foreach (range(1, $limit) as $exponent) {
        $power = bcpow($base, $exponent);
	$total = 0;

	for ($position = 0; $position < strlen($power); $position++) {
		$total += substr($power, $position, 1);

	$maxsum = max($maxsum, $total);

echo $maxsum;

Looping 1..99 and again in an inner loop for calculating the powers.  Using the BC Math function bcpow() to do the calculation.  Then looping over those digits, adding them up, and storing the maximum value of that sum of digits.


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Blog at WordPress.com.

%d bloggers like this: