Factorial of a number(n!) is the product of all positive numbers less than or equal to that number.
The formula for factorial of a number is,
n! = n * (n-1) * (n-2) * ... * 2 * 1
n! = 1 if n = 1 or 0
Based on the above formula we can generate a recursive formula,
n! = n * (n-1)!
Given a number, we have to find its factorial.
Example:
Input:
n = 6
Output:
n! = 720
Explanation:
6! = 6*5*4*3*2*1 = 720
The program will use this formula to find the factorial. As find factorial is a repetitive process. We have two methods to solve this problem,
- Using iteration
- Using recursion
1) Recursive Approach to find factorial of a number
In recursion, we will call the same method multiple times until a condition is not satisfied.
Here, we will call the function factorial(n) in the following way:
Program:
Output
2) Iterative approach to find factorial of a number
In iteration, we will loop over a sequence of numbers and multiply the number to result variable to find factorial.
Program:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer