Shriphani ‘PSP’ Palakodety

Weblog of an Aspiring Computer Scientist

Shriphani ‘PSP’ Palakodety header image 2

Why me worry ?…..

February 9th, 2008 · 3 Comments · Mathematics, python

Shaun ( of #computers on irc.icq.net ) once mentioned that children are quite clever till people teach them things. I am currently in such a state. I’ve got ignorant people, ignorant about their ignorance, all around me and what’s more, this super-brain society feels that it is up to them to set me on the path to success. When you set their skills to test, they confuse between Perl and vim and feel that programming includes just taking things into consideration and typing instructions in English. I am just cheesed off by this lot. What do I do when I am in am in this towering temper ? I code. Well, let us begin this technical dose guaranteed to bring calm and quiet to the oppressed mind.

During my search for good number theory questions ( not already included in the Project Euler problem archive ). I discovered Kaprekar’s brilliant work.

Observe the following numbers:

(a). 197:

Arrange the digits of 197 in increasing order and you get 179. Reverse this and you get 971. 971-179 = 792. Do the same with 792.

972-279 = 693

963-369 = 594

954-459 = 495

STOP ! 495 is the kaprekar constant for 3 digit numbers. Pick any 3 digit number and carry out the aforementioned process. You will end up at 495. This is called the Kaprekar method. I hacked up a Python script to measure the depth of the Kaprekar process. It supports 3 digit numbers only atm. I will hack it up a bit more to figure out the kaprekar constant and then calculate the depth. So fellow code enthusiasts, enjoy !;

#!/usr/bin/python 

#Kaprekar process length

from copy import copy 

kaprekar_constant = 495 

def kapLength(number): 

        difference = numAppend(number)[2] 

        i = 0 

        while difference != kaprekar_constant: 

                i = i + 1 

                difference = numAppend(difference)[2] 

        else: 

                return i 

def numAppend(number): 

        numlist = [] 

        for char in str(number): 

                numlist.append(char) 

        numlist.sort() 

        new_numlist = copy(numlist) 

        new_numlist.reverse() 

        smallest_number = int("".join(numlist)) 

        greatest_number = int("".join(new_numlist)) 

        difference = greatest_number - smallest_number 

        return (smallest_number, greatest_number, difference) 

print kapLength(197)

Change the number in the last argument to try out new numbers. I will write about something I have stumbled upon in the world of semantic filesystems tomorrow.

Tags:

3 Comments so far ↓

Leave a Comment