Efficiently Calculating Factorials in Python

clock icon

asked 2 days ago Asked

message

0 Answers

eye

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?

0 Answers

Write your answer here

Top Questions