The factorial of a number n (written as n!) is the product of all positive integers from 1 to n.
Example:
5! = 5 Γ 4 Γ 3 Γ 2 Γ 1 = 120
The general formula is:
n! = n Γ (n-1) Γ (n-2) Γ ... Γ 1
By definition, 0! = 1
.
Simple Factorial Function
function factorial(n) {
if (n === 0 || n === 1) return 1;
return n * factorial(n - 1);
}
Example: Calculate factorial(4)
Step-by-step breakdown:
factorial(4)
= 4 Γ factorial(3)
= 4 Γ (3 Γ factorial(2))
= 4 Γ (3 Γ (2 Γ factorial(1)))
= 4 Γ (3 Γ (2 Γ 1))
= 4 Γ (3 Γ 2)
= 4 Γ 6
= 24
On code:
console.log(factorial(4)); // Output: 24
Top comments (0)