Skip to content

Instantly share code, notes, and snippets.

@web20opensource
Last active August 29, 2015 14:17
Show Gist options
  • Save web20opensource/19806120eea9dda056de to your computer and use it in GitHub Desktop.
Save web20opensource/19806120eea9dda056de to your computer and use it in GitHub Desktop.
The max safe integer representation in js is a Happy Number :) . Number.MAX_SAFE_INTEGER
var myHN = function (){
var happyClosure = function(number){
//started at
var timeStamp = new Date().getTime();
//save original number
var happyNumber = number;
//iterations done
var iterNumber = 0;
//create digits' array from the given number
var convertStr2Array = function(number){
return Array.prototype.slice.call(number.toString(),function(digit){
return Number(digit);
});
}
// test if the string has a binary structure
// if is like a binary string then number is a happy number
var isBinaryString = function(number) {
return /^[1]+[0]*$/.test(number);
};
//return the sum of squares
var sumAll = function (arrStr) {
var sum =0;
for (var i = 0; i < arrStr.length; i++) {
sum += Math.pow(arrStr[i], 2);
}
return sum;
};
return function(){
var rightNow = new Date().getTime();
var secs = (rightNow - timeStamp)/1000;
if ( secs <= 5 && ( (iterNumber++) !== 299999) ){
number = sumAll(convertStr2Array(number));
if (isBinaryString(number) ){
//enough, is a happy number
return {'isHappyNumber':true , 'mayIContinue':false};
}
}else{
var sadNumber = happyNumber;
console.log("The time is up (%d iterations done)."+
" The elapsed time is %d secs"+
" I can't know if %d is happy or sad... :( "
, iterNumber, secs, sadNumber);
return {'isHappyNumber':false, 'mayIContinue':false};
}
return {'isHappyNumber':false,'mayIContinue':true};
};
}
var closure = happyClosure(arguments[0]);
if (typeof closure === 'function'){
do{
var result = closure();
}
while(result.mayIContinue);
}
return result.isHappyNumber;
};
console.log("Max safely represented integer in js " + Number.MAX_SAFE_INTEGER +" is a Happy number :) " + myHN(Number.MAX_SAFE_INTEGER) );
@web20opensource
Copy link
Author

create function myHN to calculate if a number is happy. Abort the mission after 300000 iterations or 5 seconds elapsed whatever comes first.

Use a closure to wrap in its own scope each calculation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment