Created
June 16, 2011 12:02
-
-
Save jonelf/1029099 to your computer and use it in GitHub Desktop.
Kaprekar's constant
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[i, o, n, e] = [0, '', prompt('Enter a number between 1 and 9998 whose digits are not all identical'), ''] | |
while n!=6174 | |
n = e + n | |
q = (n='0'+n if !n[3]) for x in [0..2] | |
n ?= q | |
o+=n+"\n" if i | |
a = n.split(e).sort().join(e) | |
n = a.split(e).reverse().join(e) | |
o += n + ' - ' + a + ' = ' | |
n-=a | |
i++ | |
alert(o + "6174\nIt took " + i + " iterations to reach Kaprekar's constant.") |
Kaprekar showed that 6174 is reached in the limit as one repeatedly subtracts the highest and lowest numbers that can be constructed from a set of four digits that are not all identical. - http://en.wikipedia.org/wiki/D._R._Kaprekar#Kaprekar_constant
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test run here http://alicebobandmallory.com/kaprekars_constant.html