We will be writing two JavaScript functions, the job of both the functions will be to take in a number and return its factorial.
The first function should make use of a for loop or while loop to compute the factorial. Whereas the second function should compute the factorial using a recursive approach.
Lastly, we should compare the times taken by these functions over a large number of iterations.
Example
Following is the code −
const factorial = (num = 1) => {
let result = 1;
for (let i = 2; i <= num; i += 1) {
result *= i;
}
return result;
}
const factorialRecursive = (num = 1) => {
if(num > 1){
return num * factorialRecursive(num - 1);
}else{
return 1;
}
};
const ITERATIONS = 100000000;
const num = 12;
console.time('Looping Approach');
for(let i = 0; i < ITERATIONS; i++){
factorial(num);
};
console.timeEnd('Looping Approach');
console.time('Recursive Approach');
for(let j = 0; j < ITERATIONS; j++){
factorialRecursive(num);
};
console.timeEnd('Recursive Approach');Output
Following is the output on console −
Looping Approach: 886.720ms Recursive Approach: 6526.203ms
This time taken will vary from machine to machine by the ratio is bound to remain more or less the same.