Debugging: reading errors and fixing broken code

The most important skill a developer has isn't writing code — it's reading code that's broken and understanding why.

The function below is supposed to return the factorial of n (n! = n × (n-1) × … × 1, and 0! = 1). But it has three bugs:

  1. The base case is wrong
  2. The return value is wrong
  3. The recursive call is wrong

Find and fix all three.

// Broken
function factorial(n: number): number {
  if (n === 1) return 0;          // bug 1
  return n + factorial(n - 2);   // bugs 2 & 3
}

Your program receives a single integer. Print its factorial.

Input:  5
Output: 120

Constraints

  • Must use recursion (not a loop).
  • Handle n=0 correctly (0! = 1).
Ad SpaceGoogle AdSense active for guests & free-tier learners.