A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

# My mysterious number 6174

I found an interesting article from HN regarding the 6174 number.

Quoted from this site:

In 1949 the mathematician D. R. Kaprekar from Devlali, India, devised a process now known as Kaprekar’s operation. First choose a four digit number where the digits are not all the same (that is not 1111, 2222,…). Then rearrange the digits to get the largest and smallest numbers these digits can make. Finally, subtract the smallest number from the largest to get a new number, and carry on repeating the operation for each new number.

It is a simple operation, but Kaprekar discovered it led to a surprising result. Let’s try it out, starting with the number 2005, the digits of last year. The maximum number we can make with these digits is 5200, and the minimum is 0025 or 25 (if one or more of the digits is zero, embed these in the left hand side of the minimum number). The subtractions are:

5200 – 0025 = 5175
7551 – 1557 = 5994
9954 – 4599 = 5355
5553 – 3555 = 1998
9981 – 1899 = 8082
8820 – 0288 = 8532
8532 – 2358 = 6174
7641 – 1467 = 6174

When we reach 6174 the operation repeats itself, returning 6174 every time. We call the number 6174 a kernel of this operation. So 6174 is a kernel for Kaprekar’s operation, but is this as special as 6174 gets? Well not only is 6174 the only kernel for the operation, it also has one more surprise up it’s sleeve. Let’s try again starting with a different number, say 1789.

9871 – 1789 = 8082
8820 – 0288 = 8532
8532 – 2358 = 6174

We reached 6174 again!

I was bored so I spent a few minutes with my Zend Studio and made this little program to come up with 6174 for every number you enter.

```< ?php \$number = "2990"; \$big = process(\$number,true); \$small = process(\$number); \$diff = '';   \$steps = 1; while(\$diff != "6174") { \$diff = (int)\$big - (int)\$small; echo \$big." - ".\$small." = ".\$diff."n"; \$big = process(\$diff,true); \$small = process(\$diff); \$steps ++; } echo "nIt took ".\$steps." steps to reach ".\$diff."...";   function process(\$number,\$big = false) { \$number = str_split(\$number); if(\$big) rsort(\$number); else sort(\$number); return implode(\$number); } ?>```
This entry was posted in General and tagged . Bookmark the permalink.

### One Response to My mysterious number 6174

1. Wenbert says:

Hehe earlier today I found out that there is a function in PHP that will reverse a string I am too lazy to update my code, but I can now do away with the rsort() and use strrev() instead. More details on strrev() here: http://www.php.net/strrev 