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 number on the final corner is going to be $N^2$.

For even $N$, it'll be the bottom left corner, for odd, the top right.

For odd $N$, e.g. $N = 5$: $$ 1 $$ $$ + 3^2 + (3^2 - 3*1 + 1) + (3^2 - 3*2 + 2) + (3^2 - 3*3 + 3) $$ $$ + 5^2 + (5^2 - 5*1 + 1) + (5^2 - 5*2 + 2) + (5^2 - 5*3 + 3) $$

where the 3 additional terms to the right of $i^2$ accounts for the other 3 sides of the square (i.e. the other members on the diagonals).

For even $N$, e.g. $N = 4$: $$ 0 $$ $$ + 2^2 + (2^2 - 2*1 + 1) + (2^2 - 2*2 + 2) + (2^2 - 2*3 + 3) $$ $$ + 4^2 + (4^2 - 4*1 + 1) + (4^2 - 4*2 + 2) + (4^2 - 4*3 + 3) $$

for odd $N$: $$1 + \sum_{i=1}^{\frac{N-1}{2}} \left\{ 4(2i + 1)^2 - (2i + 1)(1 + 2 + 3) + (1 + 2 + 3)\right\} $$ $$ = 1 + \sum_{i=1}^{\frac{N-1}{2}} \left\{ 16i^2 + 16i + 4 - 12i - 6 + 6 \right\} $$ $$ = 1 + \sum_{i=1}^{\frac{N-1}{2}} \left\{ 16i^2 + 4i + 4 \right\} $$ $$ = 1 + 16\sum_{i=1}^{\frac{N-1}{2}}i^2 + 4\sum_{i=1}^{\frac{N-1}{2}}(i+1)$$ $$ = (1 + 4\frac{N-1}{2}) + 16\frac{\frac{N-1}{2}(\frac{N-1}{2} + 1)(2\frac{N-1}{2} + 1)}{6} + 4\frac{\frac{N-1}{2}(\frac{N-1}{2} + 1)}{2} $$ $$ = -1 + 2N + \frac{1}{2}(N-1)(N+1) + \frac{2}{3}(N-1)(N)(N+1) $$ and for even $N$: $$\sum_{i=1}^{\frac{N}{2}} \left\{ 4(2i)^2 - (2i)(1 + 2 + 3) + (1 + 2 + 3)\right\}$$ $$ = 16\frac{\frac{N}{2}(\frac{N}{2} + 1)(2\frac{N}{2} + 1)}{6} - 12\frac{\frac{N}{2}(\frac{N}{2} + 1)}{2} + 6\frac{N}{2}$$ $$ = 3N - \frac{3}{2}N(N+2) + \frac{2}{3}N(N+1)(N+2)$$


In [1]:
def diag_sum(n):
    if n % 2 == 1:
        return -1 + 2*n + ((n-1)*(n+1))/2 + (2*(n-1)*n*(n+1))/3
    else:
        return 3*n - (3*n*(n+2))/2 + (2*n*(n+1)*(n+2))/3

assert diag_sum(n=5) == 101
assert diag_sum(n=4) == 7+1+3+13+16+4+2+10

In [7]:
diag_sum(n=10000001)


Out[7]:
666666916666710000001L

In [ ]: