Last active
April 23, 2020 08:19
-
-
Save sayanriju/69d94accca6dc8a55912d80aa9600804 to your computer and use it in GitHub Desktop.
Calculate Kaprekar's Constant
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isSame(str1, str2) { | |
return String(str1).split('').sort().join('') === String(str2).split('').sort().join('') | |
} | |
function kaprekar(num, seed = num, iterations = 0) { | |
const digits = String(num).padStart(String(seed).length, '0').split('') | |
const big = Number(digits.sort().reverse().join('')) | |
const small = Number(digits.sort().join('')) | |
const diff = big - small | |
if (isSame(num, diff)) return console.log(seed, iterations, diff) | |
kaprekar(diff, seed, iterations + 1) | |
} | |
for (let i = 100; i <= 999; i++) { | |
kaprekar(i) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment