Project Euler with Ruby on WSL [Problem 28]

力づくで解けると

それはそれで気分がいい

問題

Number spiral diagonals

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?

私訳

整数の方形螺旋

1 から時計回りに螺旋を描いて 5 x 5 の方形をつくると上の図のようになる

この図の対角の和(強調している部分)は 101 になる

1001 x 1001 の方形螺旋の対角の和はいくつか?

解答方針

9 までは 1,3,5,7,9 と 2 つ飛ばし、その次は 9,13,17,21,25 と 4 つ飛ばしになってますねー

ということは、次は 6 つ飛ばしになる。

n x n とその周りを取り巻く (n+2) x (n+2) の方形を考えると、 外周は 2 x (2n+2) = 4(n+1) 個になるので、 外側の四隅の数は n+1 個の差がある、ということですな

で、これをあとは 3~101 まで実行すればいいと