Euler 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

$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?

I would try to create a function $f(n)$ which yields the sum of the outmost ring of a n by n spiral.

For example:

$f(1) = 1$

$f(3) = 3 + 5 + 7 + 9 = 24$

$f(5) = 13 + 17 + 21 + 25 = 76$

When we have this function we calculate the solution simply by

s = sum([f(n) for n in range(1, 1002, 2)])

For each outer ring there is an initial corner value c ($c_3 = 3, c_5 = 76$). Once we have this value we can caluclate f like $f(n) = c_{n} + (c_n + n - 1) + (c_n + 2(n-1)) + (c_n + 3(n-1)) = 4c_n + 6 (n-1)$

In [ ]:
def f(n):
    if n == 1:
        return 1
    return 0

s = sum([f(n) for n in range(1, 1002, 2)])
assert(s == 669171001)
s