Create a function that calculates the factorial of a number.
- User
Create a function that calculates the factorial of a number.
Assistant
Create a function that calculates the factorial of a number.
The user wants a function to calculate the factorial of a number.
math.factorial.This method is generally more memory-efficient and easier to understand.
def factorial_iterative(n):
# Check if the number is negative
if n < 0:
return "Factorial does not exist for negative numbers"
# Initialize result to 1 (since 0! is 1)
result = 1
# Multiply numbers from 1 to n
for i in range(1, n + 1):
result *= i
return result
# Example usage:
num = 5
print(f"The factorial of {num} is {factorial_iterative(num)}")
# Output: The factorial of 5 is 120
This method calls the function within itself. It is mathematically elegant but can hit memory limits (recursion depth errors) with very large numbers.
def factorial_recursive(n):
# Check if the number is negative
if n < 0:
return "Factorial does not exist for negative numbers"
# Base case: 0! and 1! are both 1
if n == 0 or n == 1:
return 1
# Recursive case: n * factorial of (n-1)
else:
return n * factorial_recursive(n - 1)
# Example usage:
num = 5
print(f"The factorial of {num} is {factorial_recursive(num)}")
# Output: The factorial of 5 is 120
If you are using Python specifically for a project, the standard library math module has a highly optimized built-in function for this:
import math
print(math.factorial(5)) # Output: 120