In [ ]:
"""
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?"""

In [34]:
# Seems to be Ulam's spiral

# 1001*1001 = 1002001 is the total number of numbers

# need a way to select all numbers on the diagonals
# 3.5.7.9...13...17...21...25.....
# so jump 1,1,1,1,3,3,3,3,5,5,... and so on, all odd numbers, because each spiral 'arm' adds two rows and two columns

In [36]:
def spiralSum(maxInt):
    '''Returns the sum of diagonal numbers on number spiral up to and including maxInt.'''
    diagnums = set()
    diagnums.add(1)

    jumpcounter = 0 
    jumpgoal = 1 
    jumpsdone = 0 

    for i in range(2,maxInt+1):
        if jumpcounter == jumpgoal:
            diagnums.add(i)
            jumpcounter = 0 
            jumpsdone += 1
            if jumpsdone == 4:
                jumpgoal += 2
                jumpsdone = 0 
        else:
            jumpcounter += 1
    return(sum(diagnums))

In [37]:
spiralSum(1002002)


Out[37]:
669171001