In this Python example, we will discuss the different ways to find the factorial of any given number
1. What is Factorial of a Number?
The factorial of a number is the function that multiplies the number by every natural number below it.– Cuemath
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n
Input : 4!
Output : 24
Explanation : 4 * 3 * 2 * 1
Input : 6!
Output : 720
Explanation : 6 * 5 * 4 * 3 * 2 * 1
Some of the topics which will be helpful for understanding the program implementation better are:
Let’s implement different ways and understand one by one.
2. Python Programs to Find Factorial
There are different ways by which we can find the factorial of a number. We will go through each of the methods and see how they can be implemented.
2.1. Using The Recursion
Using the recursive method, we will make one function and the function will be called recursively.
Let’s see how it works.
#Python Program for factorial using recursion
return 1 if (n==1 or n==0) else n * factorial(n - 1);
n = 7
Factorial of 7 is 5040
In the above program, the function
factorial calls itself under the condition if n is greater than 1
2.2. Using Iteration
In this method, we will iterate the loop and multiply the provided value till it reaches 1.
# Python Program to find factorial using reursion
if n < 0:
return "Not possible"
elif n == 0 or n == 1:
f = 1
while(n > 1):
f *= n
n -= 1
n = 5
print("Factorial of", n, "is", factorial(n))
The Given Number is Odd Number
In the above program, we have made a function in which we have given the if…else… condition and if the certain condition is satisfied then the iteration will start and it will stop when the condition is false. Final value of
f will be returned.
2.3. Using In-Built Function
Inside the math module, we have the in-built function factorial, which directly returns the factorial of the provided input number value.
# Python Program to find factorial using in-built function
n = 8
print("Factorial of", n, "is", math.factorial(n))
In the above-provided program, we just call the
factorial function from the math module and pass the value for which the factorial has to be calculated.
In this article, we discussed the different ways by which we can find the factorial of the given number. We have used a recursive function and inbuild function to find out the factorial of any given number in python.
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! 😊