Code Logo

Calculate Factorial Recursively

Published at19 Apr 2026
Recursion Easy 4 views
Like0

The factorial is a mathematical operation that turns a single number into a cascade of multiplications. Represented by an exclamation mark, like n!, it is calculated by multiplying a number by every positive integer smaller than itself.

Think of it as counting the number of ways you can arrange a set of items. If you have 5 books on a shelf, there are 5 * 4 * 3 * 2 * 1 (or 120) different ways to organize them. By mathematical convention, the factorial of 0 is defined as 1.

The beauty of the factorial is that it follows a nested pattern: 5! is really just 5 multiplied by 4!. This recursive relationship makes it one of the most famous examples for learning how a function can call itself to solve a bigger problem.

Learn about our pseudocode specification
Guide

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

Solving a factorial recursively is all about trusting that the function will eventually reach a stopping point. In recursion, we call this the base case.

For this challenge, our base case is when the input reaches 0. At that point, the function simply returns 1. For any other number, we multiply that number by the result of calling the factorial function again with n - 1.

function factorial(n)
   if n = 0 then
      return 1
   else
      return n * factorial(n - 1)
   endif
endfunction

This creates a chain of pending multiplications. If you call factorial(4), the computer waits to finish 4 * factorial(3), which waits for 3 * factorial(2), and so on. Once it hits the base case, the answers ripple back up, eventually giving you the final result of 24.

Best Answers

Pseudocode - Approach 1
function factorial(n: integer) -> integer
dictionary
algorithm
   if n = 0 then
      return 1
   else
      return n * factorial(n - 1)
   endif
endfunction

program calculate_factorial_recursive
dictionary
   n: integer
algorithm
   input(n)
   output(factorial(n))
endprogram