Skip to content

Instantly share code, notes, and snippets.

@jonelf
Created June 16, 2011 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonelf/1029099 to your computer and use it in GitHub Desktop.
Save jonelf/1029099 to your computer and use it in GitHub Desktop.
Kaprekar's constant
[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.")
@jonelf
Copy link
Author

jonelf commented Jun 16, 2011

@jonelf
Copy link
Author

jonelf commented Jun 16, 2011

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