Skip to content

Instantly share code, notes, and snippets.

@xk
Created February 10, 2014 23:35
Show Gist options
  • Select an option

  • Save xk/8926445 to your computer and use it in GitHub Desktop.

Select an option

Save xk/8926445 to your computer and use it in GitHub Desktop.
Faster Happy Numbers JavaScript
//2014-02-10 jorge@jorgechamorro.com Happy Numbers JavaScript
function sumaCuadrados (n) {
var d, r= 0;
while (n) n-= (d= n % 10), r+= d*d, n/= 10;
return r;
}
function isHappy (n) {
while (n && n!=1 && n!=4 && n!=16 && n!=37 && n!=58 && n!=89 && n!=145 && n!=42 && n!=20)
n= sumaCuadrados(n);
return n == 1;
}
var i, ctr= 0;
for (i=0 ; i<10000000 ; i++) isHappy(i) && ctr++;
console.log(ctr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment