Calculate Factorial Recursively
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.
Example Input & Output
5 * 4 * 3 * 2 * 1 = 120.
4 * 3 * 2 * 1 = 24.
By definition, 0! = 1.
Algorithm Flow

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.
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
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))
endprogramComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
