// cache values of results of happy numbers so don't have to recalculate
var happyNumberMap = {};
function isHappyNumber(num) {
//var pastCalculations = []; // recent calculations
var currentNumber = num;
var currentList = [];
// prevent crashing and infinite loops
var iterator = 1000;
while (currentNumber != 1) {
iterator--;
if (iterator <= 0) {
return 'you fucked up';
break;
}
var stringNumber = "" + currentNumber;
var happyNumber = 0;
// if currentList does not have the number so we haven't run into it
if (currentList.indexOf(currentNumber) < 0) {
currentList.push(currentNumber);
if (!happyNumberMap.hasOwnProperty(stringNumber)) {
for (var i=0; i<stringNumber.length; i++) {
happyNumber += Math.pow(parseInt(stringNumber[i]), 2);
}
happyNumberMap[stringNumber] = happyNumber;
} else {
happyNumber = happyNumberMap[stringNumber];
}
} else {
// we calculated already so its not a happyNumber
return false;
}
currentNumber = happyNumber;
}
return true;
}
var arrayOfNumbers = [];
for (var i=1; i<=243; i++) {
if (isHappyNumber(i)) {
arrayOfNumbers.push(i);
}
}
console.log(arrayOfNumbers);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.