Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 18

Implement a simple recursive function with a base case

Medium

17 minute session

Summary

Implement recursion with a clear base case by writing a factorial function.

Problem statement

Implement factorial(n) that returns n! (n factorial) for non-negative integers using recursion. The base case is n == 0 which returns 1. Validate input: n must be an integer and non-negative; raise TypeError for non-integers and ValueError for negative integers. Use recursion for the general case.

Task

Write a recursive factorial(n) function that handles base cases and validates input.

Examples

Factorial of 4

Input

factorial(4)

Output

24

Explanation

4! = 4 * 3 * 2 * 1 = 24; recursion reduces n until base case 0.

Input format

A single integer n passed to factorial(n).

Output format

Return an integer equal to n!. The returned value will be converted to a string for comparison.

Constraints

Use recursion with a base case n == 0. Validate that n is a non-negative integer.

Samples

Sample input 0

factorial(5)

Sample output 0

120

Explanation 0

5! = 120

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

09:03 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.