Skip to content

Instantly share code, notes, and snippets.

@xk xk/happyNumbers.js

Created Feb 10, 2014
Embed
What would you like to do?
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
You can’t perform that action at this time.