Stack Overflow Prevention - Problem
Write a recursive function that calculates the factorial of a number with a built-in depth limit to prevent stack overflow. The function should throw a custom error when the recursion depth exceeds the specified limit.
Requirements:
- Implement a recursive factorial function with a depth counter
- Throw a custom error message when depth limit is exceeded
- Return the factorial result if computation succeeds within the limit
Custom Error Format: "Error: Recursion depth limit exceeded"
Input & Output
Example 1 — Successful Calculation
$
Input:
n = 5, maxDepth = 10
›
Output:
120
💡 Note:
Factorial of 5 is 5! = 5 × 4 × 3 × 2 × 1 = 120. Recursion depth is 5, which is less than maxDepth of 10, so calculation succeeds.
Example 2 — Depth Limit Exceeded
$
Input:
n = 8, maxDepth = 5
›
Output:
Error: Recursion depth limit exceeded
💡 Note:
Calculating 8! would require 8 recursive calls, but maxDepth is only 5, so the function throws an error before stack overflow occurs.
Example 3 — Edge Case at Limit
$
Input:
n = 3, maxDepth = 3
›
Output:
6
💡 Note:
Factorial of 3 requires exactly 3 recursive calls, which matches maxDepth of 3. This is the boundary case where calculation just succeeds.
Constraints
- 1 ≤ n ≤ 20
- 1 ≤ maxDepth ≤ 100
- Function must track recursion depth accurately
- Error message must match exactly: "Error: Recursion depth limit exceeded"
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code