Factorial¶
Abstract
This lesson presents the factorial calculation problem using recursion.
Problem statement¶
Task:
Using recursion, write a program to calculate \(n!\).
Given that \(0! = 1\) and \(1! = 1\).
Input:
A non-negative integer \(n\).
Output:
An integer representing the factorial of \(n\).
Test cases:
| No. | Input | Output |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 1 | 1 |
| 3 | 6 | 720 |
| 4 | 21 | 51090942171709440000 |
Proposed solution¶
Core idea
We have the recurrence relation for calculating the factorial as follows:
According to the formula above:
-
Base case: \(n = 0\) or \(n = 1\).
No further recursive calls are made; the function simply returns
1. -
Recursive case: all remaining values of \(n\) (assuming \(n\) is not a negative integer).
The function calls itself with
n - 1as the parameter to calculate \((n - 1)!\), and then multiplies the result by \(n\).Example:
To calculate \(5!\), the function calls itself to compute \((5 - 1)! = 4!\), and then multiplies the result by \(5\).Specifically:
- The
factorial(5)function recursively callsfactorial(4). - The
factorial(4)function recursively callsfactorial(3). - The
factorial(3)function recursively callsfactorial(2). - The
factorial(2)function recursively callsfactorial(1). - The
factorial(1)function makes no further recursive calls and returns1.
- The
Writing the program
1. Write the factorial() function with a single parameter n.
2. Write the main program:
- Prompt the user to enter a non-negative integer and store it in the variable
number. - Call the
factorial()function withnumberas the argument and store the returned value in the variableresult. - Print the result.
3. Run the program and enter 6; the output is as follows:
Source code¶
The complete source code is available at: