Factorial of a Number in Python
Factorial of a Number in Python
Here we will discuss how to find the Factorial of a Number in Python programming language.
Factorial of any number is the product of it and all the positive numbers below it for example factorial of 5 is 120
Factorial of n (n!) = 1 * 2 * 3 * 4....n
5! = 1 x 2 x 3 x 4 x 5 = 120 7! = 1 x 2 x 3 x 4 x 5 x 6 x 7 = 5040
Ways discussed:-
- Iterative approach
- Recursive approach
Method 1 (Iterative)
Python Code
Run
num = 6 fact = 1 # Factorial of negative number doesn't exist if num < 0: print("Not Possible") else: for i in range(1, num+1): fact = fact * i print("Factorial of", num, "is", fact) # Time complexity: O(N) # Space complexity: O(1)
Output
Factorial of 6 is 720
Method 2 (Recursive)
This method uses recursion in Python
Python Code
Run
def getFactorial(num): if num == 0: return 1 return num * getFactorial(num - 1) num = 6 fact = getFactorial(num) print("Factorial of", num, "is", fact) # Time complexity: O(N) # Space complexity: O(1) # Auxiliary Space complexity(Function call stack): O(N)
Output
Factorial of 6 is 720
For similar Questions click on the given button
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
number = int(input(“Enter the number: “))
num = 1
if number<=0:
print("factorial is not possible")
else:
for i in range(1,number+1):
num = num*i
print(num)