Problem
This problem comes from Project Euler 28
Problem
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
![]()
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?
Solution
Let’s notice a few things:
- In the first “ring,” the numbers 3, 5, 7, and 9 go up by two
- In the second “ring,” the numbers 13, 17, 21, and 25 go up by four
We can see that every “corner” increases by . Therefore, we can calculate the total by calculating each corner and adding that to the total.
Code
# Project Euler: Problem 28
# Number Spiral Diagonals
total = 1 # "ring" 0
corner = 1 # "corner" of "ring" 0
for ring in range(1, 501):
for _ in range(0, 4):
corner += 2*ring # 3, 5, 7, 9, 13...
total += corner # 1, 4, 9, 16, 25...
print(total)