null
0
0
Efficiently Calculating Factorials in Python
asked 2 days ago Asked
0 Answers
2 Views
I'm trying to create a simple Python program that calculates the factorial of a number. I've written the following code:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
num = int(input("Enter a non-negative integer: "))
result = factorial(num)
print("The factorial of", num, "is", result)
However, when I input a large number like 20, the program takes a long time to execute. Is there a more efficient way to calculate factorials in Python?