2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

カプレカ数を求めるプログラム

2
Posted at

カプレカ数を求めるプログラムを,とりあえずPythonで作成してみました.なお,ここで言うカプレカ数は,Wikipediaのカプレカー数の定義2に沿ったものです.

桁を並べ替えて最大にした数と最小にした数との差を取ったとき、元の値に等しくなる自然数(カプレカー定数を含む)。

カプレカ数の紹介例としては『最大と最小の差分を繰り返し適用すると,どんな3桁でもカプレカ数495に収束,どんな4桁でもカプレカ数6174に収束,5桁は収束せずカプレカ数なし,6桁は549945と631764のみカプレカ数で他は収束しない』といったものが多いのですが,収束しない場合はループとなるので,これらの結果を全てカバーするリスト型で出力しています.なお,全ての桁が同じ場合は(当然ながら)全ての桁が0となります.

Kaprekar.py
def morder(n):
  a, b = ''.join(sorted(n, reverse=True)), ''.join(sorted(n))
  return str(int(a) - int(b)).zfill(len(n))

def Kaprekar(n):
  r, rn, nums = morder(str(n)), '', []
  while not (r in nums):
    nums += [r]
    r, rn = morder(r), r
  return nums + [r]
実行例
$ python3 -i Kaprekar.py
>>> Kaprekar(123)
['198', '792', '693', '594', '495', '495']
>>> Kaprekar(287)
['594', '495', '495']
>>> Kaprekar(2734)
['5085', '7992', '7173', '6354', '3087', '8352', '6174', '6174']
>>> Kaprekar(1726)
['6354', '3087', '8352', '6174', '6174']
>>> Kaprekar(27346)
['52965', '70983', '94941', '84942', '73953', '63954', '61974', '82962', '75933', '63954']
>>> Kaprekar(27263)
['53955', '59994', '53955']
>>> Kaprekar(123456)
['530865', '829962', '771723', '653544', '310887', '873522', '651744', '620874', '851742', '750843', '840852', '860832', '862632', '642654', '420876', '851742']
>>> Kaprekar(631764)
['631764', '631764']

(他のプログラミング言語やもっと短い記述例とかを追記したいなあと思っているけど未定)

更新履歴

  • 2026-07-19:初版公開
2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?