Skip to content

Instantly share code, notes, and snippets.

@bishil06
Created February 25, 2021 04:07
Show Gist options
  • Save bishil06/312c918b3a37377f7754f1da22738be7 to your computer and use it in GitHub Desktop.
Save bishil06/312c918b3a37377f7754f1da22738be7 to your computer and use it in GitHub Desktop.
JavaScript factorial algorithm
function forFacto(n) {
for(var i=1; n>0; i *= n--);
return i;
}
function recurFacto(n) {
if (n === 1) {
return 1;
}
return n * recurFacto(n-1);
}
function reduceFacto(n) {
return Array.from({length: n}, (_, i) => i+1).reduce((acc, v) => acc*v, 1);
}
function *range(start, end, step=1) {
while(start < end) {
yield start;
start += step;
}
}
function test(n) {
let result = 1;
for (const a of range(1, n+1)) {
result *= a;
}
return result;
}
console.log('test');
console.time()
console.log(forFacto(100));
console.timeEnd()
console.time()
console.log(recurFacto(100));
console.timeEnd()
console.time()
console.log(reduceFacto(100));
console.timeEnd()
console.time()
console.log(test(100));
console.timeEnd()
/*
test
9.332621544394418e+157
default: 0.349ms
9.33262154439441e+157
default: 0.052ms
9.33262154439441e+157
default: 0.077ms
9.33262154439441e+157
default: 0.095ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment