What is Kaprekar's Constant?
Named after the Indian mathematician D. R. Kaprekar, the number 6174 is known as Kaprekar's Constant. Kaprekar found that by recursively sorting and subtracting four-digit numbers, solutions will converge upon the number 6174.
Performing Kaprekar's Routine
The algorithm is as follows:
- Take any four-digit number, using at least two distinct digits (leading zeros are allowed).
- Arrange the digits in both descending and ascending order to get two four digit numbers, adding leading zeros if necessary.
- Subtract the smaller number from the bigger number.
- If the result is not 6174, go back to step 2 and repeat this process.
The only four-digit numbers for which Kaprekar's routine does not reach 6174 are: 0000, 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999.
Example:
Starting with the number 8991:
- 9981 - 1899 = 8082
- 8820 - 0288 = 8532
- 8532 - 2358 = 6174
Running Kaprekar's Routine
This repository contains a script for running Kaprekar's routine. Usage is as follows:
kaprekar.routine( number );
This function will return an object with the number of iterations and steps used in the routine.