Kaprekar's Constant in JavaScript
Justin Ethier
Posted on May 7, 2022
So I was scrolling TikTok's the other day, as one does, when I saw the number 6174
featured in one of the videos. Turns out this is a special number called Kaprekar's constant, named after Indian mathematician D. R. Kaprekar.
Start with a four-digit number with at least two different digits. If a number has less than four digits we can pad it with zeros. For example, 42
becomes 0042
.
- Arrange the digits from largest to smallest and again from smallest to largest to get maximum and minimum values.
- Subtract minimum from maximum.
- Repeat these steps.
The result will always converge to 6174
after a small number of iterations.
For example,
628
8620 - 268 = 8352
8532 - 2358 = 6174
It's tedious to do this work by hand, though. Let's write some code to explore Kaprekar's algorithm further!
From Concept to Code
The core algorithm may be implemented in JavaScript as follows.
First we convert a given number to a string padded with leading zeros:
> var num = 423;
> num.toString().padStart(4, '0');
'0423'
Then we split the digits into an array so we can arrange them into our minimum and maximum numbers. The array operations are performed in-place, so a new array is created for each value:
> var min = num.split('').sort()
[ '0', '2', '3', '4' ]
> var max = num.split('').sort().reverse()
[ '4', '3', '2', '0' ]
Finally we use join
to convert each array back into a string and parseInt
to convert those back to numbers so we can subtract the values:
> parseInt(min.join(''))
234
> parseInt(max.join(''))
4320
JavaScript Implementation
The final code incorporates a validate
function to reject numbers without multiple digits and runs our algorithm automatically using a random four-digit number:
But wait, there's more!
Here is a variation of the program that generates a histogram of many iterations it takes to reach 6174
for all four-digit numbers.
Running this code you can see we reach 6174
after at most seven iterations:
{ '0': 1,
'1': 383,
'2': 576,
'3': 2400,
'4': 1272,
'5': 1518,
'6': 1656,
'7': 2184 }
Conclusion
And that's it! Hope you enjoyed this fun little tidbit.
Please feel free to leave your thoughts in the comments ☀️ 😄 👍
Posted on May 7, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.