Skip to content

Instantly share code, notes, and snippets.

@xk
Created February 10, 2014 16:03
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 xk/8918502 to your computer and use it in GitHub Desktop.
Save xk/8918502 to your computer and use it in GitHub Desktop.
Happy Numbers in JavaScript
//2014-02-10 jorge@jorgechamorro.com happy numbers
String.prototype.reduce= [].reduce;
Array.prototype.has= function has (n) { return this.indexOf(n) >= 0 };
Array.prototype.times= function (f,i) { for (i= this[0] ; i<=this[1] ; i++) f(i) };
function happy (n) {
var past= [];
while (1) {
if ((n= n.toString().reduce(function(n,v){ return n+v*v },0)) === 1) return 1;
if (past.has(n)) return 0; else past.push(n);
}}
[1,1000].times(function(n) { happy(n) && console.log(n) });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment