Duncan's blog

October 7, 2014

Project Euler: problem 28 (PHP) – Number spiral diagonals

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

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

Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

21 22 23 24 25
20  7  8  9 10
19  6  1  2 11
18  5  4  3 12
17 16 15 14 13

It can be verified that the sum of the numbers on the diagonals is 101.

What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?

The wording on the question has changed slightly since when I originally did this, clarifying the exact requirements.  Here’s my PHP solution:

<?php
$total = 1;
$runningtotal = 1;

$length = 1001;

for ($i = 2; $i < $length; $i += 2) {
	for ($j = 1; $j <= 4; $j++) {
		$runningtotal += $i;

		$total += $runningtotal;
	}
}

echo $total;

Another solution where the code is simple and identical to the CFML version.

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: