へたっぴpythonista

ド素人pythonistaとして、日々の学習成果や気づいたことについて書きます。

Project Euler 55をpythonで解く

問題

If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.

Not all numbers produce palindromes so quickly. For example,

349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337

That is, 349 took three iterations to arrive at a palindrome.

Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).

Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.

How many Lychrel numbers are there below ten-thousand?

NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.

 

ある数にそれを逆さまに並べた数を足すという試行を繰り返すと、いずれ12321や4884のように数字の並びが左右どちらから読んでも同じ回文数が得られる場合がある。例えば349は

349+943=1292、1292+2921=4213、4213+3124=7337となり、3回目の試行で回文数が得られる。一方で、196のように何度試行を繰り返しても回文数にならない数も存在する。こうした数はLychrel numberと呼ばれる。

10000以下の数字の内、50回の試行で回文数が得られない数字の個数を求めよ

 

 

一般に196問題と呼ばれる問題です。Lychrel numberの最小値が196であることからこう呼ばれています。詳しくはこちら

1桁と2桁の数にLychrel numberが存在しないことは証明済みのようなので、調べる範囲は196~10000でいいようです。

 

解答

List=[]
for i in range(196,10001):

     counter=0
     num=i
     while counter<50:

          num +=int(str(num)[::-1])

          if str(num)==str(num)[::-1]:

               List.append(i)

               break

          else:

               counter +=1

print(9805-len(List))

 

forループで調べる数字をwhileループで試行を表現しました。whileループ2行目で試行を行い、ifステートメントで回文数か否かを調べます。あとは10000-196+1=9805から非Lycheral数の個数を引けば答え249が得られます。