LoginSignup
1
1

More than 3 years have passed since last update.

Project Euler 52をPythonでやってみる

Posted at

問題 52

125874を2倍すると251748となる. これは元の数125874と順番は違うが同じ数を含む.
2x, 3x, 4x, 5x, 6x が x と同じ数を含むような最小の正整数 x を求めよ.

http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%2052

解答

正直なんの工夫もなく調べていっても1秒ちょっとで解けるのですがそれじゃあ味気ないのでxと6xの桁数が一致するための必要条件として上2桁が17以下であるかの判定をしました。

ProjectEuler52.py
def check(n):
    n_sort = sorted(str(n))
    for i in range(2,7):
        if n_sort != sorted(str(i*n)):
            return False
    return True

def main():
    n_max =10000000
    for n in range(100,n_max):
        if int(str(n)[:2]) > 17: #桁チェック
            continue
        if check(n):
            return n

print(main())

0.383 seconds

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