LoginSignup
2
1

More than 5 years have passed since last update.

Project Euler 30「各桁の5乗」

Posted at

はじめてのジェネレータ関数。

Problem 30 「各桁の5乗」

驚くべきことに, 各桁を4乗した数の和が元の数と一致する数は3つしかない.

1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4

ただし, 1=1^4は含まないものとする. この数たちの和は 1634 + 8208 + 9474 = 19316 である.
各桁を5乗した数の和が元の数と一致するような数の総和を求めよ.

def hoge(num):
    # 最大値の算出
    d = 1 # 桁数
    while True:
        # 例えば 9^5*7=413343 であるため、9の5乗を7個足しても7桁には至らないことが分かる
        # このことから 9^5*6=354294 が問の条件に合致する可能性のある最大の値となる(たぶん)
        if d > len(str(9 ** num * d)):
            break
        d += 1
    max_number = 9 ** num * (d-1)
    # ジェネレータ関数を使ってみる
    def search():
        # 1=1^5は含めないので2^5(最小値)→最大値まで地道に全件走査
        for n in range(2**num, max_number+1):
            x = sum( int(m) ** num for m in str(n) )
            if n == x: yield x
    return sum(search())

print(hoge(5))

ジェネレータ関数の使い方あってますかね。

2
1
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
2
1