Kaprekar’s constant

A student talked about Kaprekar’s constant (6174) during their my favorite presentation.
Really cool.

Steps (from wikipedia):

  1. Take any four-digit number, using at least two different digits. (Leading zeros are allowed.)
  2. Arrange the digits in descending and then in ascending order to get two four-digit numbers, adding leading zeros if necessary.
  3. Subtract the smaller number from the bigger number.
  4. Go back to step 2.

Here’s an example (also from wikipedia):

For example, choose 3524:

5432 โ€“ 2345 = 3087
8730 โ€“ 0378 = 8352
8532 โ€“ 2358 = 6174

Fun right? Also fun to program, here’s the python code that tries every number from 1000 to 10000, and counts how many steps it takes to get to 6174 and puts the results in a csv file:

def largest(nstr):
    if (len(nstr) == 0):
        return ""
    elif (len(nstr)==4) and (nstr[0] == nstr[1] == nstr[2] == nstr[3]):
        return "7641"
    digit = -1
    index = 0
    for i in range(0,len(nstr)):
        if (digit < int(nstr[i])):
            digit = int(nstr[i])
            index = i
    return str(digit) + largest(nstr[0:index]+nstr[index+1:len(nstr)])
            
def kaprekarSteps(n):
    count = 0
    nstr = str(n)
    while (n != 6174):
        l = int(largest(str(nstr)))
        lstring = str(l)
        s = int(lstring[::-1])
        n = l - s
        nstr = str(n)
        while (len(nstr) < 4):
            nstr = "0" + nstr
        count += 1
    return count
f = open('kaprekar.csv','w')
c = 1000
while (c < 10000):
    f.write(str(c)+ "," + str(kaprekarSteps(c)) + "\n")
    c += 1
f.close()

Graph:
2014-09-29_11h45_18

This entry was posted in Full Posts and tagged , , . Bookmark the permalink.

One Response to Kaprekar’s constant

Leave a Reply

Your email address will not be published. Required fields are marked *