Skip to main content

Euler 0028

The Problem:

If you were to build a square starting with 1 in the middle then going right, down, left 2, up 2, right 2, and repeat, all the corner numbers would be diagonals.

On the Project Euler website there is a nice graphic that I'm not putting here.

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

Considerations and Approach:

This problem is bait. We don't have to generate a 2d structure. Instead we can observe the pattern of skipping.  
1.3.5.7.9...13...17...21...25.....30

We start with one and add 1. Every four times we add, we add 2 to the skipping distance, and we declare our square 2 larger!

The Code:

max_square = 1001

spiral = 1
square_size = 2
total = 1
while square_size + 1 <= max_square:
    for i in range(4):
        spiral += square_size
        total += spiral
    
    square_size += 2
    
print(total)