# Euler Problem 28¶

Back to overview.

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

$1 + 3 + 5 + 7 + 9 + 13 + 17 + 21 + 25 = 101$

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?

When we know the corner of a certain spiral we can calculate it's total like $f_n = 4 c_n + 6 (n - 1)$. We then only have to update the corner value for each spiral.

In [1]:

    total = 1
    current_corner = 3

    for n in range(3, 1002, 2):
        total += 4 * current_corner  + 6 * (n - 1)
        current_corner += 4 * n - 2

    s = total

In [2]:

    assert(s == 669171001)
    s

Out[2]:

    669171001

The only missing piece is how could we calculate the current corner value for a certain n. The series for this is as follows:

$c = 1, 3, 13, 31, 57, 91, 133, 183, 241, \dots$

With some experimenting it can be seen that

$c_n = (n - 1)^2 - (n - 2) = n^2 - 2n + 1 - n + 2 = n^2 - 3n + 3$.

Now, we can insert $c_n$ into $f_n$ which gives as the sum of corners for the nth spiral:

$f_n = 4n^2 - 12n + 12 + 6n - 6 = 4n^2 - 6n + 6$

In [3]:

    s = 1 + sum([4 * n * n - 6 * n + 6 for n in range(3, 1002, 2)])
    assert(s == 669171001)
    s

Out[3]:

    669171001