I previously blogged about this Project Euler puzzle nearly 6 years ago. Initially I tried solving it using ColdFusion, but its native functions couldn’t handle the large integers required, although I could have used the Java BigInteger class. Instead I ended up doing it as my first exercise in Python. Now I’ve had a go using PHP and I’d appreciate any feedback on my code.

Problem 16:

*2*^{15} = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

*What is the sum of the digits of the number 2*^{1000}?

Code:

<?php
$x = 0;
$y = bcpow(2,1000);
$length = strlen($y);
for ($i = 0; $i < $length; $i++) {
$x += substr($y, $i, 1);
}
echo $x;

So the only thing worth pointing out was I had to use *bcpow()* instead of *pow()* as that ended up just giving me an incorrect value in scientific notation, i .e. like 1.0715086071863E+301. Whereas bcpow is a function of the BCMath Arbitrary Precision Mathematics library:

*“For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.”*

And even though this is a separate ‘library’, it’s bundled with core PHP, so nothing additional required for me to load in, which seems to be quite common with PHP I’m discovering.

### Like this:

Like Loading...

*Related*

## Leave a Reply