Python中的Kaprekar常数

2025年1月5日 | 阅读 3 分钟

Kaprekar 常量是 6174。这个数字之所以独特,是因为对于任何四位数,遵循某些程序总能得到这个数字,但有一个前提条件是:数字中不能有重复的数字(例如 0000, 1111 等)。

  • “asc” 是将四个数字按升序排序并存储的结果。
  • 将四个数字按降序排序后的结果存储为数字“desc”。
  • 用较小的数字减去较大的数字(abs(asc - desc))。
  • 重复前三个步骤,直到减法的结果不等于前一个数字为止。
  • 最终,我们总是会得到 6174。

Python 实现 Kaprekar 常量

以上方法的实现如下:

代码

程序说明

附带的 Python 程序实现了 Kaprekar 的运算过程,这是一个数学过程,当应用于四位数(除了数字相同的数)时,最终会得到常数 6174。递归函数 kaprekar_recursive 接收前一个值 prev 和一个数字 n 作为输入。它将 n 的数字分解成一个列表,对它们进行排序以获得升序和降序的数字,计算它们的差值,并检查是否与之前的差值匹配。如果匹配,则函数返回此常数差值,Kaprekar 过程结束。如果不匹配,函数将递归调用,使用新的差值。

使用 Kaprekar 函数作为包装器,以初始 prev 值为 0 开始递归过程。之后,驱动代码会输出使用三个示例四位数(1000、1112 和 9812)测试该程序的​​结果。结果表明,对于所有测试的实例,该过程都收敛于 Kaprekar 常量,最终得到 6174,而与初始数字无关。

输出

6174
6174
6174
n = 2324
1) asc  = 2234
2) desc = 4322
3) Difference = 2088 
4) Repeating the above steps as the difference is not the same
as n
n = 2088
1) asc  = 0288
2) desc = 8820
3) Difference = 8532  
4) Repeating the above steps as the difference is not the same
as n.
n = 8532
1) asc  = 2358
2) desc = 8532
3) Difference = 6174  
4) Repeating the above steps as the difference is not the same
as n.
n = 6174
1) asc  = 1467
2) desc = 7641
3) Difference = 6174  
Stopping here as the difference is the same as n.
  • 时间复杂度: O (n log n),其中 n 是数字的位数。
  • 辅助空间: O (1)

下一话题Numpy 数组形状