Duncan's blog

October 1, 2014

Project Euler: problem 16 (PHP) – Power digit sum

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

16I 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:

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?


$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.


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: