2022-04-29

Kaprekar's Number (6174)

The so-called "Kaprekar's number," 6174, is a stable state of a short set of simple arithmetic operations. As usual, Wikipedia is a good place to learn about this topic. As quoted from Wikipedia, here are the (merely) four steps that generate Kaprekar's number:

  1. Take any four-digit number, using at least two different digits (leading zeros ["padding 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 and repeat.

Too simple not to try on my own.

Here's a link to my version in my Google Drive, where you should be able to run and/or download the (python in jupyter notebook) code for yourself using Google Colaboratory. At the very bottom of this page is a static HTML version of the code, in case anything gets messed up with the Google Drive or doesn't work as expected.

When you first click the previous link, you may be met with a screen like this:

Once you can get the code to show up, click in the first cell and press SHIFT+ENTER to execute the code in that cell. Politely, Google may warn you of the following:

I encourage you to read and understand the code for yourself; though I assure you I am not trying to remotely take over your computer.

Once you're executing code, this is the only cell you need to change (and you don't have to if you don't want to, everything will still work fine):

Happy iterating!


Interesting findings:

My code is so simple that it doesn't pad fewer-than-four-digit integers with zeros. This means that it is possible to encounter one-, two-, and three-digit starting values for the iterative loop. One and two digits can lead to uninteresting results; just forgive me and rerun the code. But a chance three-digit initial value (not all that rare in my code) will result in a second Kaprekar's number: 495. (Also mentioned on Wikipedia, if you were reading that webpage.)

Static HTML version (same code as linked above)