LoginSignup
7
7

More than 5 years have passed since last update.

カプレカ数をPythonで求めた

Posted at

話題だったので求めました。カプレカ数の定義はこんな感じです。

桁を並べ替えて最大にしたものから最小にしたものの差を取ったとき、元の値に等しくなるもの。
from カプレカ数 - Wikipedia

コード

python 3.5で動作確認。kaprekar.ipynbでJupyter Notebookで公開しました。

from functools import reduce

def kaprekar_function(n, digits):
    l =  [int(x) for x in list(str(n).zfill(digits))]
    l.sort()
    min_n = int(reduce(lambda x, y: x + y, [str(x) for x in l]))
    max_n = int(reduce(lambda x, y: x + y, [str(x) for x in l[::-1]]))
    return max_n - min_n

def kaprekar_routine(n):
    pre = n
    digits = len(str(n))
    suc = kaprekar_function(n, digits=digits)
    result = [pre]
    print(pre)
    print(suc)
    while suc not in result:
        result.append(suc)
        pre, suc = suc, kaprekar_function(suc, digits=digits)
        print(suc)
    return result

実行結果

>>> kaprekar_routine(3522)
3522
3087
8352
6174
6174

Out[2]:
[3522, 3087, 8352, 6174]

こんなのやっても大丈夫です。

>>> kaprekar_routine(35000000000000)
35000000000000
52999999999965
74429999996553
76554408554433
84311108888652
87776308632222
86555326644432
64331108886654
87733208766222
86555326644432

Out[4]:
[35000000000000,
 52999999999965,
 74429999996553,
 76554408554433,
 84311108888652,
 87776308632222,
 86555326644432,
 64331108886654,
 87733208766222]

周期性がある理由

鳩ノ巣原理を使うと簡単に証明できるので、略。

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