6174 - Kaprekar's Constant: Test in Python.
6174 - doesn't seem like a very interesting number at first glance but this Numberphile video shows that all four digit numbers converge to this number if the following procedure is followed:
- Start with a four digit number. (All four digits cannot be the same).
- Sort the digits in descending order -> D
- Sort the digits in ascending order -> A
- Take the difference between D and A.
- Repeat steps 1-4 with the new number -> D-A.
The answer will always converge to 6174!
I wrote a little function in python to test this out:
Example
Let's look at an example using the numbers 3 2 4 5.
difference([3,2,4,5])
Output:
Calling function with [3, 2, 4, 5]
5432-2345 = 3087
Calling function with [3, 0, 8, 7]
8730-378 = 8352
Calling function with [8, 3, 5, 2]
8532-2358 = 6174
Calling function with [6, 1, 7, 4]
7641-1467 = 6174
Converged!
3
In this case it took 3 iterations to converge to 6174.
Test for all four digit numbers.
I had to check for myself if this claim held for all four digit numbers, so I used the itertools module to test it:
Output:
Total numbers attempted: 9990
Successfully converged = 9918
Non converging: 72
[(0, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 1, 1), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 2), (1, 1, 2, 1), (1, 2, 1, 1), (1, 2, 2, 2), (2, 1, 1, 1), (2, 1, 2, 2), (2, 2, 1, 2), (2, 2, 2, 1), (2, 2, 2, 3), (2, 2, 3, 2), (2, 3, 2, 2), (2, 3, 3, 3), (3, 2, 2, 2), (3, 2, 3, 3), (3, 3, 2, 3), (3, 3, 3, 2), (3, 3, 3, 4), (3, 3, 4, 3), (3, 4, 3, 3), (3, 4, 4, 4), (4, 3, 3, 3), (4, 3, 4, 4), (4, 4, 3, 4), (4, 4, 4, 3), (4, 4, 4, 5), (4, 4, 5, 4), (4, 5, 4, 4), (4, 5, 5, 5), (5, 4, 4, 4), (5, 4, 5, 5), (5, 5, 4, 5), (5, 5, 5, 4), (5, 5, 5, 6), (5, 5, 6, 5), (5, 6, 5, 5), (5, 6, 6, 6), (6, 5, 5, 5), (6, 5, 6, 6), (6, 6, 5, 6), (6, 6, 6, 5), (6, 6, 6, 7), (6, 6, 7, 6), (6, 7, 6, 6), (6, 7, 7, 7), (7, 6, 6, 6), (7, 6, 7, 7), (7, 7, 6, 7), (7, 7, 7, 6), (7, 7, 7, 8), (7, 7, 8, 7), (7, 8, 7, 7), (7, 8, 8, 8), (8, 7, 7, 7), (8, 7, 8, 8), (8, 8, 7, 8), (8, 8, 8, 7), (8, 8, 8, 9), (8, 8, 9, 8), (8, 9, 8, 8), (8, 9, 9, 9), (9, 8, 8, 8), (9, 8, 9, 9), (9, 9, 8, 9), (9, 9, 9, 8)]
Maximum iterations to converge: 7
It works for except for 9918 out of 9990 combinations of four digits where all digits are not the same. The instances where it doesn't converge to 6174 are when 3 of the digits are the same number and the remaining digit is +/- 1 of the same number. In this cases the result from the first iteration is 999, the next one results in 0 and then the procedure cannot continue anymore.
The plot below shows the distribution of the number of iterations it takes to converge to 6174. The mode is 3 iterations and the mean 4.67.
Full code can be found on GitHub .