# Duncan's blog

## October 20, 2014

### Project Euler problem 56 (PHP) – Powerful digit sum

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

I 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?

Code:

```<?php
\$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.