DEV Community

OneDev
OneDev

Posted on

EXTRA: Factorial of a number - n!

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
Enter fullscreen mode Exit fullscreen mode

The general formula is:

n! = n Γ— (n-1) Γ— (n-2) Γ— ... Γ— 1
Enter fullscreen mode Exit fullscreen mode

By definition, 0! = 1.

Simple Factorial Function

function factorial(n) {
  if (n === 0 || n === 1) return 1;
  return n * factorial(n - 1);
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

On code:

console.log(factorial(4)); // Output: 24
Enter fullscreen mode Exit fullscreen mode

Top comments (0)