Kaprekar’s Constant.

Just recently I came across ‘Kaprekar’s Constant‘ and maybe Mr Kaprekar had too much spare time… but still, it is quite interesting. The idea is to take a 4 digit number where the digits are not all the same then make the largest and smallest numbers possible with these digits, subtract the smaller from the larger then rinse and repeat with the result of the subtraction.

e.g start with 4123

    \begin{align*} 4321 - 1234 = 3087 \\ 8730 - 0378 = 8352 \\ 8532 - 2358 = 6174 \\ 7641 - 1467 = 6174 \\ ... repeats... \end{align*}

and in fact all 4 digits ‘converge’ to 6174!
Now this is too good an opportunity for some Haskell…

First let’s take an integer and extract its digits into a list.

This looks a little terse because it is! It’s in ‘point free’ style so there’s really an implicit Integer argument. Dissecting it a little…What does show do? show :: a -> String So we’re mapping read . return over a string. What does read do? Well read is the ‘opposite’ of show. read :: Read a => String -> a The return function puts a value into a monadic context – in this case the list monad. So the end result is a list of digits.

Here’s the rest of the code along with an implementation of the Kaprekar algorithm.

The kap function is recursive and we use our prior knowledge of the fact that once the value 6174 is reached for a 4 digit input there’s no need to continue – line 14. And the remainder of the algorithm is very much how I described it. We sort the digits – ascending and descending to give min and max values and then get the difference. All done recursively via this line kap n = n : kap n'
And here are some example runs of kap.

We can in fact generalise this to numbers of more than 4 digits. i.e. We won’t use ‘6174’ as a terminating condition but rather we would test that the number to be added to a list of generated numbers has not actually been ‘seen’ before. This is kap’

Very much the same except we have a different terminating condition – we check for repetition rather than a particular value – and we accumulate the values in an initially empty list. So here’s a few examples.

And because we’re using Integer rather than Int we can try some really big numbers…

Or some really big numbers…

So why does the sequence sooner or later hit a cycle and from then on it repeats? Well each number in the series uniquely defines the next number and as there are only a finite – ‘tho possibly large number of alternatives – then sooner or later the numbers will repeat.

Well that’s it really – just an interesting exercise about something that’s probably not very useful! Here’s the whole code in one block.

The code is on Github here.

Thanks for reading…

Leave a Reply

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

ˆ Back To Top