LoginSignup
2
1

More than 5 years have passed since last update.

Project Euler 28「螺旋状に並んだ数の対角線」

Posted at

ジーっと眺めて閃いちゃえば後は簡単。

Problem 28 「螺旋状に並んだ数の対角線」

1から初めて右方向に進み時計回りに数字を増やしていき, 5×5の螺旋が以下のように生成される:

image.png

両対角線上の数字の合計は101であることが確かめられる.
1001×1001の螺旋を同じ方法で生成したとき, 対角線上の数字の和はいくつか?

def hoge(num):
    ans = 1 # 1は最初に加算しておく
    # 3, 5, 7, ..., 1001 という風にnを奇数としてループ
    for n in range(3, num+1, 2):
        # 四隅を加算
        for m in range(4):
            ans += n ** 2 - (n - 1) * m
    return ans

print(hoge(1001))

この位なら私でもワンライナーでいけちゃう。
上のをそのまま1行にしただけ。

sum([ n**2 - (n-1) * m for n in range(3, num+1, 2) for m in range(4) ]) + 1
2
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1