In number theory, Kaprekar's routine is an iterative algorithm that, with each iteration, takes a natural number in a given number base, creates two new numbers by sorting the digits of its number by descending and ascending order, and subtracts the second from the first to yield the natural number for the next iteration. It is named after its inventor, the Indian mathematician D. R. Kaprekar. Kaprekar showed that in the case of four-digit numbers in base 10, if the initial number has at least two distinct digits, after seven iterations this process always yields the number 6174, which is now known as Kaprekar's constant. Definition and properties The algorithm is as follows: Choose any natural number in a given number base . This is the first number of the sequence. Create a new number by sorting the digits of in descending order, and another number by sorting the digits of in ascending order. These numbers may have leading zeros, which are discarded (or alternatively, retained). Subtract to produce the next number of the sequence. Repeat step 2. The sequence is called a Kaprekar sequence and the function is the Kaprekar mapping. Some numbers map to themselves; these are the fixed points of the Kaprekar mapping, and are called Kaprekar's constants. Zero is a Kaprekar's constant for all bases , and so is called a trivial Kaprekar's constants. All other Kaprekar's constant are nontrivial Kaprekar's constants. For example, in base 10, starting with 3524, with 6174 as a Kaprekar's constant. All Kaprekar sequences will either reach one of these fixed points or will result in a repeating cycle. Either way, the end result is reached in a fairly small number of steps. Note that the numbers and have the same digit sum and hence the same remainder modulo . Therefore, each number in a Kaprekar sequence of base numbers (other than possibly the first) is a multiple of . When leading zeroes are retained, only repdigits lead to the trivial Kaprekar's constant. Families of Kaprekar's constants In base 4, it can easily be shown that all numbers of the form 3021, 310221, 31102221, 3...111...02...222...1 (where the length of the "1" sequence and the length of the "2" sequence are the same) are fixed points of the Kaprekar mapping. In base 10, it can easily be shown that all numbers of the form 6174, 631764, 63317664, 6...333...17...666...4 (where the length of