JS Built-ins
Algorithmsbeginner

Factorial

πŸ“– Usage Example
function factorial(n) {
  return n <= 1 ? 1 : n * factorial(n - 1);
}
factorial(5); // 120

Factorial uses recursion: multiply n by factorial(n-1) until the base case n<=1.

Factorial

Factorial of a number n (written as n!) is the product of all positive integers less than or equal to n.

5! = 5 Γ— 4 Γ— 3 Γ— 2 Γ— 1 = 120
0! = 1 (by definition)

This is a classic example of recursion: the base case is n ≀ 1, and the recursive case is n Γ— factorial(n-1).

function factorial(n: number): number {
  // Return n!
}

factorial(5) // 120
factorial(0) // 1
πŸ’‘ Hints (3)
  • β€’ Base case: if n ≀ 1, return 1.
  • β€’ Recursive case: return n Γ— factorial(n - 1).
  • β€’ Use the ternary operator for conciseness.