DEV Community

RamR
RamR

Posted on

2

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay