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);
}
const n1 = 5;
factorialRecursive(n1); //output: 120
const n2 = 22;
factorialRecursive(n2); //output: 1124000727777607680000
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;
}
const n1 = 5;
factorialIterative(n1); //output: 120
const n2 = 22;
factorialIterative(n2); //output: 1124000727777607680000
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);
}
const n1 = 5;
factorialTailRecursive(n1); //output: 120
const n2 = 22;
factorialTailRecursive(n2); //output: 1124000727777607680000
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);
}
const n1 = 5;
factorialArrayMapReduce(n1); //output: 120
const n2 = 22;
factorialArrayMapReduce(n2); //output: 1124000727777607680000
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;
}
const n1 = 5;
factorialWhileLoop(n1); //output: 120
const n2 = 22;
factorialWhileLoop(n2); //output: 1124000727777607680000
See the factorial of a number n, written as n!, is found by multiplying all whole numbers from 1 up to n.
For example:
5!=5×4×3×2×1=120
3!=3×2×1=6
Factorial of 5 is 120. You can run these functions to check.
No factorial of a number can not be calculated for negative integers. Only Positive integers