Factorial (recursion)

Easy TimeO(n) SpaceO(n)

The factorial of a number is that number multiplied by every whole number below it, down to 1, so 5 factorial is 5 × 4 × 3 × 2 × 1 — 120. Given a number n, zero or greater, return n!. 0! is 1, not 0.

Examples

Example 1

Input
n = 5
Output
120
5 × 4 × 3 × 2 × 1 = 120.

Example 2

Input
n = 0
Output
1
An empty product is 1, so 0! is 1 and not 0.

The Code

function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
factorial(5);
Done
Step through factorial(5) call by call