Algorithm LogbookAlgorithm Logbook

Recursion Factorial

Recursion

๐Ÿ“‹ Problem Statement

Write a function factorial(n) that returns n!n! (n factorial). n!=nร—(nโˆ’1)ร—(nโˆ’2)ร—โ‹ฏร—1n! = n \times (n-1) \times (n-2) \times \cdots \times 1. By definition, 0!=10! = 1. Input: 5 โ†’ Output: 120. You must use recursion โ€” no for or while loops allowed.

๐Ÿ’ก Intuition

Recursion breaks a problem into smaller versions of itself. Factorial has a natural recursive definition: n!=nร—(nโˆ’1)!n! = n \times (n-1)!. The base case is 0!=10! = 1. Each recursive call reduces nn by 1, and results multiply on the way back up the call stack.

๐Ÿ”ง Approach

  1. Base case: if n=0n = 0, return 1.
  2. Recursive case: return nร—factorial(nโˆ’1)n \times \text{factorial}(n - 1).
  3. Validate: raise an error for negative numbers (factorial is undefined for n<0n < 0).

โšก Complexity Analysis

Time

O(N)O(N) โ€” we make NN recursive calls, each doing O(1)O(1) work

Space

O(N)O(N) โ€” the call stack holds NN frames at its deepest point

โš ๏ธ Common Mistakes

  • Forgetting the base case (n=0n = 0), causing infinite recursion and a stack overflow
  • Using n=1n = 1 as the base case, which makes factorial(0) recurse infinitely
  • Not handling negative inputs (factorial undefined for n<0n < 0)
  • Confusing recursion depth with time complexity โ€” they are both O(N)O(N) here

๐ŸŽฏ Final Thoughts

Factorial is the "Hello World" of recursion. It teaches the two essential components: a base case that stops recursion, and a recursive case that reduces the problem. Watch out for Python's default recursion limit of 1000 for large NN.