Skip to content

Instantly share code, notes, and snippets.

@slofurno
Created April 6, 2017 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slofurno/1d1d457675af8d494e49681d2555e1a9 to your computer and use it in GitHub Desktop.
Save slofurno/1d1d457675af8d494e49681d2555e1a9 to your computer and use it in GitHub Desktop.
function kaprekar(n) {
const asc = [].slice.call('000' + n).slice(-4).sort((a,b) => a - b).join('')|0
const des = [].slice.call('000' + n).slice(-4).sort((a,b) => b - a).join('')|0
return des - asc
}
function iterations(n) {
let i = 0
while(n != 6174) {
n = kaprekar(n)
i++
}
return i
}
function valid(n) {
const s = '' + n
for(let i = 1; i < s.length; i++) {
if(s[i] != s[i-1]) { return true }
}
return false
}
let max = 0
for(let i = 1000; i <= 9999; i++) {
if (valid(i)) {
max = Math.max(max, iterations(i))
}
}
console.log(max)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment