The factorial of a non-negative integer n
, denoted by n!
is the product of all the integers less than or equal to that number.
Syntax for factorial number is:
n! = n.(n - 1).(n - 2).(n - 3)....3.2.1.
For example, the factorial of 5 (denoted as 5!) is
5! = 5.4.3.2.1 = 120
The factorial of 0!
is 1
, according to the convention for an empty product.
The Factorial operation in many mathematical areas is used in permutations and combinations, algebra and mathematical analysis.
Factorial Program in Python
We are using three ways to calculate factorial number:
• Using a function from the math module
• Iterative approach
• Recursive approach
Factorial program in python using the function
We may import a python module known as math that contains virtually any math function. To use a function to calculate the factorial, here is the code:
# Python program to find the factorial of a given number. # change the value for a different result import math # Enter the value from the user num = int(input("Enter the number: ")) print("factorial of ",num,": ",end="") print(math.factorial(num))
Output :
Factorial program in python using for loop (Iterative approach)
def factorial(n): //function definition fact=1 if int(n) >= 1: for i in range (1,int(n)+1): fact = fact * i return fact num = int(input("Enter the Number: ")) print("factorial of ",num,": ",end="") print(factorial(num))
Output :
Factorial program in python using recursion
In this case, we are defining a user-defined function factorial()
. This function finds the factorial of a given number by calling itself repeatedly until the base case reach.
# Python program to find the factorial of a number using recursion def factorial(n): if n == 1: return n else: return n*factorial(n-1) # take input from the user n = int(input("Enter the number : ")) print("factorial of ",n," : ",end="") print(factorial(n))
Output :