# Duncan's blog

## October 7, 2014

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

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

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

Advertisements

## Leave a Comment »

No comments yet.

Blog at WordPress.com.