Computing Factorials
Explore how to compute factorials using recursion in C++. Learn the concept of factorials, understand the base and recursive cases in the function, and see step-by-step code implementation to solidify your understanding for coding interviews.
What is a factorial?
A factorial is the product of an integer and all the positive integers less than it. It is denoted by the symbol:
For example, 4! (read as four factorial) is denoted as follows:
Expanding a Factorial
A factorial of any integer can be written as a product of that integer and the factorial of the integers less than it. For example, can be written as follows:
Important Note: Factorials only exists for positive numbers. The factorial of 0 is equal to 1.
Mathematical Notation
The factorial of a number can be written in the form shown below:
The generic mathematical notation for computing a factorial is:
We will now use the recursive function concept for computing the factorial of a number.
Code Implementation
The code below shows how to implement a factorial with recursion. First, let’s look at the code, then we can go on to its explanation.
Try changing the value of “input” below in order to see different outputs
Understanding the code
In the code above, the function, factorial, is a recursive function as it makes a recursive call. Below is an explanation of the above code:
Driver Function
-
Inside the
int main()code, we have defined an integer variable, at line 21, namedinput. -
In the next line, line 23, we are computing the factorial using the function
factorial, and storing the answer returned from it in the variable,result. The data type ofresultisdouble, which is the same as the return type of the functionfactorial. -
In line 24, we are printing the computed factorial.
Recursive Function
To cater for large factorials, in line 4, we have specified the return type of this function as double. This function takes an integer, n, as the input argument.
Base Case
- The base case of the function is being defined in line 7 where the function will terminate and return 1 when the
ifcondition ofn==0orn==1is met. This is because the factorial of or is equal to and a factorial cannot go below this.
Recursive Case
-
If the base case condition does not evaluate to true, the function then enters the
elseblock where it recursively calls itself with the input argumentn-1instead ofn, as seen in line 14. This is because of the following factorial expansion:
Understanding Through a Stack
Now that you have learned about computing factorial using recursion, we will solve another interesting mathematical problem in the next lesson, the sum of integers from 1 to n.