Created
February 10, 2014 16:03
-
-
Save xk/8918502 to your computer and use it in GitHub Desktop.
Happy Numbers in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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