Code Logo

Calculate Factorial Recursively

Published at19 Apr 2026
Easy 0 views
Like0

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:

factorial(n) = 1, if n = 0 factorial(n) = n * factorial(n - 1), if n > 0

So the task is to read n, compute its factorial with a recursive function, and print the result.

Example Input & Output

Example 1
Input
n = 5
Output
120
Explanation

5 * 4 * 3 * 2 * 1 = 120.

Example 2
Input
n = 4
Output
24
Explanation

4 * 3 * 2 * 1 = 24.

Example 3
Input
n = 0
Output
1
Explanation

By definition, 0! = 1.

Algorithm Flow

Recommendation Algorithm Flow for Calculate Factorial Recursively
Recommendation Algorithm Flow for Calculate Factorial Recursively

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:

return n * factorial(n - 1)

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.