Kaprekar’s Routine
Take any 4-digit number (not all digits the same). Sort digits descending, sort ascending, subtract. Repeat. You always reach 6174 — Kaprekar’s constant — in at most 7 steps. Watch it happen.
What’s happening
Kaprekar’s routine
In 1949, Indian mathematician D.R. Kaprekar discovered a surprising property of 4-digit numbers. Take any 4-digit number where not all digits are the same. Sort its digits in descending order to get the largest possible arrangement, then sort ascending for the smallest. Subtract the smaller from the larger. Repeat with the result. Within at most 7 iterations, you always arrive at 6174 — and 6174 maps to itself: 7641 − 1467 = 6174.
The algorithm
function kaprekar(n):
pad n to 4 digits
desc = sort digits descending (e.g. 3087 → 8730)
asc = sort digits ascending (e.g. 3087 → 0378)
return desc - asc (8730 - 378 = 8352)
Why does it converge?
There is no simple algebraic proof — convergence was verified computationally for all 4-digit inputs. The routine acts as a contraction mapping on a finite set: 6174 is the unique fixed point. The 3-digit version converges to 495 (e.g. 954 − 459 = 495). Not all digit lengths have a single fixed point: 2-digit numbers cycle, and some bases or digit counts produce cycles instead of fixed points.
The histogram
The histogram shows how many valid starting numbers take each number of steps to reach the fixed point. For 4-digit numbers, no starting value takes more than 7 steps. The distribution is not uniform — most numbers converge in 3–5 steps, with very few taking 1 or 7.
Extensions
The 3-digit analogue converges to 495 in at most 6 steps. For other digit lengths the behavior varies: 5-digit numbers don’t have a single fixed point but instead reach cycles. Kaprekar’s routine has been studied in other number bases too — base 5, base 16 — each with its own constants and cycle structures.