Duncan's blog

September 26, 2014

Project Euler: problem 8 (PHP) – Largest product in a series

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

88888888I previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Problem 8:

The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.

Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

This question has been slightly changed since I originally did this. Previously it was the product of 5 adjacent digits; now it’s the product of 13 adjacent digits.

$digits = <<<FOO

$max = 0;
$limit = 13;

// turn this into a single-line string
$digits = str_replace(["\n", "\r"], "", $digits);

for ($i = 0; $i < strlen($digits); $i++) {
	$sum = 1;
	// multiply together our 13 digits
	for ($j = 0; $j < $limit; $j++) {
		$sum *= substr($digits, $i + $j, 1);
	if ($sum > $max) {
		$max = $sum;

echo $max;

So I’m using the Heredoc syntax, equivalent to cfsavecontent, for a multi-line string. I’m not sure if it would be advantageous in this case to use Nowdoc, or even just appending each line to a single string, but for now Heredoc seems simple and does what I’m looking for.

I expect there’s some de facto convention for what to use for the end identifier (the bit after the <<< and again at the end of the string), but for now FOO will suffice.   Is it covered in any of the PSR coding standards?

So I get rid of the newline and carriage return characters from the string, turning it into one single line string.  Initially I tried doing str_replace([‘\n’, ‘\r’], “”, $digits) except that didn’t work because it didn’t like the single quoted characters.  Instead I had to double-quote them, obviously!

Again we find inconsistencies in PHP, this time with the naming of the functions, str_replace() but strlen(), being the equivalent of ColdFusion’s replace() and len().

And substr(string, start[, count]) being more fully-featured than CFML’s mid(string, start, count).  If you use negative numbers it can extract starting from the end of the string.  And if you don’t specify the count parameter, it goes up to the end of the string.


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: