Write a JavaScript function to find factorial of a number. You can use recursive approach, tail-recursive approach and iterative approach
You can understand factorial on byjus website
Input: n = 5
Output: 120
Input: n = 22
Output: 1124000727777607680000
function factorialRecursive(number) {
if (number < 0) {
throw new Error("Factorial cannot be calculated for negative values.");
}
if (number === 0 || number === 1) {
return 1;
}
return number * factorialRecursive(number - 1);
}function factorialIterative(number) {
if (number < 0) {
throw new Error("Factorial cannot be calculated for negative values.");
}
let product = 1;
for (let i = 2; i <= number; i++) {
product *= i;
}
return product;
}function factorialTailRecursive(number, accumulator = 1) {
if (number < 0) {
throw new Error("Factorial cannot be calculated for negative values.");
}
if (number === 0 || number === 1) {
return accumulator;
}
return factorialTailRecursive(number - 1, accumulator * number);
}function factorialArrayMapReduce(number) {
if (number < 0) {
throw new Error("Factorial cannot be calculated for negative values.");
}
return [...Array(number + 1).keys()]
.slice(1)
.reduce((product, current) => product * current, 1);
}function factorialWhileLoop(number) {
if (number < 0) {
throw new Error("Factorial cannot be calculated for negative values.");
}
let product = 1;
let i = 2;
while (i <= number) {
product *= i;
i++;
}
return product;
}