Python BasicsMedium

Factorial using recursion

Detailed guide and Python implementation for the 'Factorial using recursion' problem.

Problem Statement

Medium

Write a function factorial(n) that computes the factorial of a non-negative integer n using recursion. The factorial of n (written as n!) is the product of all positive integers from 1 to n. By definition, 0! = 1. The function should return the factorial as an integer.

Constraints
  • 0 <= n <= 20

Examples

Example 1
Input
n = 5
Output
120
Explanation

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

Example 2
Input
n = 0
Output
1
Explanation

0! is defined as 1.

Example 3
Input
n = 7
Output
5040
Explanation

7! = 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040.

Need a Hint?
Consider using Recursion-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.