Factorial the Recursive Way

Easy ⏱ 8 min 88% acceptance ★★★★☆ 4.4
Implement factorial(n) recursively (no loops) that returns n! for a non-negative integer n. The base case is n <= 1, which returns 1.

Examples

Example 1
Input
factorial(5)
Output
120
Explanation

5 * 4 * 3 * 2 * 1 = 120.

Example 2
Input
factorial(0)
Output
1
Explanation

Base case: 0! is defined as 1.

Constraints

  • 0 <= n <= 20
  • Must use recursion, not a loop.

Topics

RecursionMath

Companies

AmazonTCSInfosys

Hints

Hint 1

The base case is n <= 1, returning 1.

Hint 2

The recursive case is n * factorial(n - 1).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.