Calculate Factorial Recursively
This problem introduces a classic recursive idea. You are given one non-negative integer n, and your task is to calculate n!, which is called the factorial of n.
Factorial means multiplying all positive integers from 1 up to n. For example, 5! means 5 * 4 * 3 * 2 * 1, so the answer is 120. By definition, 0! is 1.
This problem is a natural fit for recursion because factorial can be defined in terms of a smaller factorial:
So the task is to read n, compute its factorial with a recursive function, and print the result.
Example Input & Output
5 * 4 * 3 * 2 * 1 = 120.
4 * 3 * 2 * 1 = 24.
By definition, 0! = 1.
Algorithm Flow

Solution Approach
A recursive solution works by breaking the problem into a smaller version of itself.
The most important part is the base case. If n = 0, the factorial is already known, which is 1. This stops the recursion.
For any value greater than 0, use the recursive rule:
That means if you want factorial(4), you calculate 4 * factorial(3). Then factorial(3) becomes 3 * factorial(2), and so on, until the call reaches factorial(0).
Once the base case returns 1, the calls finish in reverse order and build the final answer. For example, factorial(4) becomes 4 * 3 * 2 * 1 * 1 = 24.
The full algorithm is: read n, call a recursive function such as factorial(n), and print the result. The recursion depth is n, so the running time is O(n).
Best Answers
Solutions Coming Soon
Verified best solutions for this Challenge are still being analyzed and will be available soon.
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
