0
0

【Project Euler】Problem 9: 特別なピタゴラス数

Last updated at Posted at 2022-01-06
  • 本記事はProjectEulerの「100番以下の問題の説明は記載可能」という規定に基づいて回答のヒントが書かれていますので、自分である程度考えてみてから読まれることをお勧めします。

問題 9. ピタゴラス数

原文 Problem 9: Special Pythagorean triplet

問題の要約:ピタゴラス数の3つの数の和が1000となるもの3つの積を求めよ

ピタゴラス数はProject Eulerではよく出てくるので、今後のために基本ピタゴラス数を無限に発生させる関数pythを作ります。

import itertools, math
def pyth():
  for m in itertools.count(2):
    for n in range(1,m):
      if (m%2)==(n%2): continue
      if math.gcd(m,n) != 1: continue
      yield m*m - n*n, 2*m*n, m*m + n*n

g = pyth()
for i in range(5):
  print(next(g))
#(3, 4, 5)
#(5, 12, 13)
#(15, 8, 17)
#(7, 24, 25)
#(21, 20, 29)

後は3つの和の倍数が1000になるものを見つければよいだけです。

import numpy as np
g = pyth()
while True:
  p = next(g)
  s = sum(p)
  if 1000 % s == 0:
    m = 1000 // s
    ansp = np.array(p)*m
    break

print(f"Answer : {ansp.prod()}, {ansp}")

(開発環境:Google Colab)

0
0
0

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
0
0