1
\$\begingroup\$

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 (21, 7, 1, 3, 13, 25, 9, 5, 17].

What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?

def calculate_diagonals_rec(n):
    """Assumes n an odd integer.
    returns total of diagonals of a spiral matrix of size n * n."""
    total = 1
    if n == 1:
        return total
    right_up = n * n
    left_up = right_up - n + 1
    left_down = left_up - n + 1
    right_down = left_down - n + 1
    total += (right_up + right_down + left_up + left_down)
    return total + calculate_diagonals_rec(n - 2)

And for larger numbers:

def calculate_diagonals_iter(n):
    """Assumes n an odd integer.
    returns total of diagonals of a spiral matrix of size n * n"""
    total = 1
    for i in range(n, 1, -2):
        right_up = i * i
        left_up = right_up - i + 1
        left_down = left_up - i + 1
        right_down = left_down - i + 1
        total += (right_up + right_down + left_up + left_down)
    return total


if __name__ == '__main__':
    print(calculate_diagonals_rec(1001))
    print(calculate_diagonals_iter(5001))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.