Just curious to know is there any other alternative way to achieve this Kaprekar constant program.
var num = 4455, n1, n2, i = 0;
for (i; num > 999 && num < 10000 && num !== 6174; i++) {
n1 = +(("" + num).split("").sort((a, b) => a - b).join(""))
n2 = +(("" + num).split("").sort((a, b) => b - a).join(""))
num = n2 - n1;
console.log(n2, "-", n1, "=", num);
}
console.log(i, "steps")
expanded
var num = 4455;
var arr, arr1, arr2;
var n1, n2, result;
var i;
for (i = 0; num !== 6174 && num > 999 && num < 10000; i++) {
arr = ("" + num).split("")
arr1 = [...arr].sort((a, b) => a - b)
arr2 = [...arr].sort((a, b) => b - a)
//console.log(arr1);
//console.log(arr2);
n1 = Number(arr1.join(""))
n2 = Number(arr2.join(""))
result = n2 - n1;
num = result;
console.log(n2, "-", n1, "=", result);
}
console.log(i, "steps");
Top comments (2)
So the meaning of life is 6174…. And not 42? I feel lied to.
Kidding. Great piece, love these kinds of topics!
Thanks