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 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

Apr 28, 2025 - 14:13
 0
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

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