A # Kaprekar constant

Take any four-digit number whose digits are not all identical. Rearrange the string of digits to form the largest and smallest 4-digit numbers possible. Take these two numbers and subtract the smaller number from the larger. Use the resulting number and repeat the process. For example, starting with 3141: 4311 - 1134 = 3177, 7731 - 1377 = 6354, 6543 - 3456 = 3087, 8730 - 0378 = 8352, 8532 - 2358 = 6174, 7641 - 1467 = 6174. After this, the result is always 6174. Remarkably, every four-digit number whose digits are not all the same will eventually reach 6174, in at most seven steps, and then stay there. This is called the Kaprekar constant for four-digit numbers, after the Indian mathematician Dattathreya Ramachandra Kaprekar who made the discovery in 1949.

The Kaprekar constant for three-digit numbers is 495, which is arrived at for any three-digit number in no more than six iterations. The same process, or algorithm, can be applied to numbers of n digits, where n is any whole number. Depending on the value of n, the algorithm will result in a non-zero constant, zero (the degenerate case), or a cycle.