Skip to content

Instantly share code, notes, and snippets.

@dwf
Created August 23, 2010 01:39
Show Gist options
  • Save dwf/544590 to your computer and use it in GitHub Desktop.
Save dwf/544590 to your computer and use it in GitHub Desktop.
Messing around with Kaprekar's procedure.
def kaprekar(s, t=4):
"""
Demonstrate Kaprekar's procedure and its convergence to Kaprekar's constant.
"""
s = str(s)
# t = 3 or 4 will converge; otherwise all bets are off.
assert len(s) <= t
if len(s) < t:
s = ('0' * (t - len(s))) + s
print s
old = None
new = int(''.join(sorted(s))[::-1]) - int(''.join(sorted(s)))
while old != new:
old = new
s = str(new)
if len(s) < t:
s = ('0' * (t - len(s))) + s
print s
new = int(''.join(sorted(s))[::-1]) - int(''.join(sorted(s)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment