Calculating Factorial in Python
The factorial of a non-negative integer \( n \) is the product of all positive integers less than or equal to \( n \). It is denoted by \( n! \). For example, \( 5! = 5 \times 4 \times 3 \times 2 \times 1 = 120 \). By definition, \( 0! = 1 \).
Here’s how to implement a function in Python to calculate the factorial of a number using both iterative and recursive approaches.
Iterative Method
The iterative method uses a loop to calculate the factorial:
def factorial_iterative(n):
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
result = 1
for i in range(2, n + 1):
result *= i
return result
Recursive Method
The recursive method calls the function itself with a smaller number until it reaches the base case:
def factorial_recursive(n):
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
if n == 0:
return 1
return n * factorial_recursive(n - 1)
Usage
To use either of these functions, simply call them with a non-negative integer:
# Example usage
number = 5
print(f"Iterative: {number}! = {factorial_iterative(number)}")
print(f"Recursive: {number}! = {factorial_recursive(number)}")
Error Handling
Both methods include error handling for negative input. Attempting to calculate the factorial of a negative number raises a ValueError.
Conclusion
These implementations provide a clear and efficient way to compute the factorial of a number in Python, utilizing both iterative and recursive techniques. Factorials grow rapidly, so it's advisable to handle larger values cautiously to avoid performance issues or exceeding recursion limits.