Here is the Python code to calculate the factorial of a number. The factorial of a non-negative integer \( n \) (denoted as \( n! \)) is the product of all positive integers less than or equal to \( n \).
### 1. Iterative Approach
This method uses a loop to multiply the numbers.
```python
def factorial_iterative(n):
if n < 0:
return "Factorial does not exist for negative numbers"
result = 1
for i in range(1, n + 1):
result *= i
return result
# Example usage
number = 5
print(f"The factorial of {number} is {factorial_iterative(number)}")
```
### 2. Recursive Approach
This method calls the function within itself to calculate the result.
```python
def factorial_recursive(n):
if n < 0:
return "Factorial does not exist for negative numbers"
if n == 0 or n == 1:
return 1
else:
return n * factorial_recursive(n - 1)
# Example usage
number = 5
print(f"The factorial of {number} is {factorial_recursive(number)}")
```
### 3. Using the Built-in `math` Module
Python has a built-in library optimized for this calculation.
```python
import math
number = 5
print(f"The factorial of {number} is {math.factorial(number)}")
```
Would you like me to explain how these methods work in more detail, or do you need the code in a different programming language like C++ or Java?
We use cookies to enhance your browsing experience and analyze site traffic. By continuing to use our site, you consent to our use of cookies, including those from third parties (Google Analytics). For more information, please see our Terms of Service and Privacy Policy.