Kaprekar constant calculator
Reply #21 –
Kaprekar's constant is number 6174. It is to do with the feature of four-digit numbers that after sorting the four-digit number from the largest digit to smallest and subtracting from it the same number sorted from the smallest digit to largest, and repeating the process, then soon enough, in max seven steps, the result is 6174.
There are four-digit numbers that resolve to Kaprekar's constant in one single step. Kaprekar's constant 6174 itself is among them. The procedure is as follows:
1. Sort a four-digit number from the largest digit to the smallest, e.g. 6174 becomes 7641
2. Sort the same four-digit number from the smallest digit to the largest, i.e. 6174 becomes 1467
3. Subtract the larger number from the smaller, i.e. 7641-1467=6174.
4. If the result is other than 6174, repeat the entire process with the result until it becomes 6174.
The four-digit number needs to have at least two different digits, because anything like e.g. 8888-8888 or 2222-2222 would be an immediate zero with nowhere else to go. However, leading zeros are allowed. For example 8760-0678 and 1000-0001 are valid Kaprekar operations.
(defun kaprekar-calculator (num)
"Calculate the number of steps to Kaprekar's constant for a
given four-digit number."
(interactive "nGive a 4-digit number: ")
(let* ((given (number-to-string (abs num)))
(numlength (length given))
(numstring (cond ((< 4 numlength)
(string-limit given 4))
((> 4 numlength)
(concat (make-string (- 4 numlength) ?0)
given))
(t given))))
(require 'cl-lib)
(if (equal (cl-sort numstring '>) (cl-sort numstring '<))
(message "The given number must have at least two different digits")
(if (equal "6174" numstring)
(message "6174 is Kaprekar's constant!")
(let ((result 0)
(varstring numstring))
(require 'calc)
(while (not (equal "6174" varstring))
(if (equal "999"
(calc-eval
(concat (cl-sort varstring '>)
"-" (cl-sort varstring '<))))
(progn
(setq varstring "6174")
(setq result (+ 5 result)))
(progn
(setq varstring
(calc-eval
(concat (cl-sort varstring '>)
"-" (cl-sort varstring '<))))
(setq result (1+ result)))))
(if (eq result 1)
(message "%s resolves to Kaprekar's constant in one step"
numstring)
(message "%s resolves to Kaprekar's constant in %d steps"
numstring result)))))))
After minimal manual verification, it seems to work. I have not run into numbers that take more than seven steps. Indeed more than seven steps should not be possible, so I guess it's calculating correctly.