Skip to content

Instantly share code, notes, and snippets.

@surajhell88
Last active May 20, 2018 16:49
Show Gist options
  • Save surajhell88/e899ae986adfeba6c141b47c17db22a8 to your computer and use it in GitHub Desktop.
Save surajhell88/e899ae986adfeba6c141b47c17db22a8 to your computer and use it in GitHub Desktop.
Calculate Attempts until Kaprekar's Constant from a 4-digit Integer

Get Attempts until Kaprekar's Constant

Given a 4-digit integer to the function, calculate the number of attempts until it reaches kaprekar's constant i.e. 6174

Few Examples

  1. KaprekarsConstant(8) // 6
  2. KaprekarsConstant(1324) // 3
  3. KaprekarsConstant(3322) // 4
var numOfAttempts = 0;
function addRemainingZeros(number) {
var remaining = 4 - number.length;
for(var i = 0; i < remaining; i++) number += '0';
return number;
}
function KaprekarsConstant(num) {
var numAsString = num + ''; // convert integer to string
if (numAsString.length < 4) {
numAsString = addRemainingZeros(numAsString);
}
numOfAttempts += 1;
var aesc = parseInt(numAsString.split('').sort(function(a, b) { return a - b; }).join(''));
var desc = parseInt(numAsString.split('').sort(function(a, b) { return b - a; }).join(''));
var substract = desc > aesc ? desc - aesc : aesc - desc;
return substract === 6174 ? countOfAttempts : KaprekarsConstant(substract);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment