Skip to content

Instantly share code, notes, and snippets.

@pherris
Created January 24, 2014 02:41
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 pherris/8591182 to your computer and use it in GitHub Desktop.
Save pherris/8591182 to your computer and use it in GitHub Desktop.
var magicNumberFinder = (function () {
var knownMagicNumbers = [], cacheUsedCount = 0, cacheSize = 0;
function stringImpl(num) {
var sum = 0,
prod = 1,
currentNum = "",
stringNum = ""+num;
for (i=0;i<stringNum.length;i++) {
currentNum = parseInt(stringNum.charAt(i));
sum += currentNum;
prod = prod*currentNum;
}
return sum === prod;
}
function modImpl (num) {
var sum = 0,
prod = 1,
mod;
while (num>=10) {
mod = num%10;
num = Math.floor(num/10);
sum += mod;
prod = prod*mod;
}
//a little ugly doing this once more out of the loop.
sum += num;
prod = prod*num;
return sum === prod;
}
return {
isMagic: function (num, method) {
// console.log(num);
//if it is known, don't recalculate
if (knownMagicNumbers[num] === undefined) {
if (!method) {
knownMagicNumbers[num] = modImpl(num);
} else {
knownMagicNumbers[num] = stringImpl(num);
}
cacheSize++;
} else {
cacheUsedCount++;
}
return knownMagicNumbers[num];
},
cacheStats: function (maxLoops) {
console.log("cache size: " + cacheSize + ", used " + cacheUsedCount + " times");
console.log("cache used: " + (cacheUsedCount/maxLoops)*100 + "%");
},
wipeCache: function () {
knownMagicNumbers = [], cacheUsedCount = 0, cacheSize = 0;
}
}
}());
function testIt(method) {
var loopCount = 0;
var maxLoops = 10000000;
console.log((method?"STRING":"MOD") + " - creating " + maxLoops + " random numbers to see if they are magic");
var start = new Date();
while (loopCount<maxLoops) {
magicNumberFinder.isMagic(Math.floor(Math.random()*maxLoops), method);
loopCount++;
}
var end = new Date();
magicNumberFinder.cacheStats(maxLoops);
console.log("time taken (ms) : " + (end.getTime() - start.getTime()));
console.log("------------------------------");
}
testIt();
magicNumberFinder.wipeCache();
testIt("s");
//console.log(magicNumberFinder.isMagic(22));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment