Kaprekar calculator in Emacs Lisp

Kaprekar’s constant is the number 6174. It is the result of Kaprekar calculations, which are applicable to Kaprekar numbers.

A Kaprekar number is a four-digit number with at least two different digits. That is, any four-digit number is good, but for example 1111 or 2222 (repetition of a single digit) is inapplicable. At the same time, leading zeroes are allowed, for example 0001 is acceptable.

In a Kaprekar calculation, a Kaprekar number is sorted from largest digit to smallest and also from smallest digit to largest, and then a subtraction is performed. Then another Kaprekar calculation is performed with the result. In a few steps, maximum seven steps, the result will be Kaprekar constant, 6174.

For example, performed with Kaprekar’s constant itself, the operation looks like:

  1. The original four-digit number is 6174.
  2. Digits sorted from largest to smallest: 7641
  3. Digits sorted from smallest to largest: 1467
  4. The calculation: 7641-1467=6174

Kaprekar calculations do not provide any deep mathematical insight or revelation. They are just for fun, answering the question “How many steps does it take for this four-digit number to resolve into Kaprekar’s constant?” Kaprekar’s constant resolves to itself instantly in a single step.

Similarly just for fun, here is an Emacs Lisp function that takes a number, performs Kaprekar calculations on it and outsputs the number of steps it took to get to Kaprekar’s constant. (The input should be a four-digit number, but the function attempts some conversions with other numerical inputs.)

Leave a Reply