Duncan's blog

October 3, 2014

Project Euler: problem 20 (PHP) – Factorial digit sum

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

20I previously blogged about this Project Euler puzzle nearly 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 20:

n! means n x (n − 1) x … x 3 x 2 x 1

For example, 10! = 10 × 9 × … × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!

Code:

<?php
$limit = 100;
$total = 0;
$product = 1;

for ($i = $limit; $i > 1; $i--) {
	$product = bcmul($product, $i);
}

$length = strlen($product);

for ($i = 0; $i < $length; $i++) {
	$total += substr($product, $i, 1);
}

echo $total;

So here using the BCMath library’s bcmul() function to multiply arbitrarily large numbers, as PHP’s arithmetic operators can’t handle anything over 2^32.

Advertisements

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

Create a free website or blog at WordPress.com.

%d bloggers like this: