DEV Community

RamR
RamR

Posted on

Kaprekar constant 6174 JavaScript

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")
Enter fullscreen mode Exit fullscreen mode

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");

Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (2)

Collapse
 
martinbaun profile image
Martin Baun

So the meaning of life is 6174…. And not 42? I feel lied to.
Kidding. Great piece, love these kinds of topics!

Collapse
 
raguram90 profile image
RamR

Thanks