Ref Math Factorial
## Python math.factorial() Method
The `math.factorial()` method is a built-in function in Python's standard `math` module. It is used to calculate and return the factorial of a given non-negative integer.
The factorial of a number $n$ (denoted as $n!$) is the product of all positive integers less than or equal to $n$. For example, the factorial of 6 is calculated as:
$$\text{6!} = 6 \times 5 \times 4 \times 3 \times 2 \times 1 = 720$$
---
### Syntax
To use this method, you must first import the `math` module:
```python
import math
math.factorial(x)
```
### Parameters
* **`x`** (Required): A non-negative integer.
* If `x` is a negative number or a floating-point number, the method raises a `ValueError`.
* If `x` is not a numeric type (e.g., a string), the method raises a `TypeError`.
### Return Value
* Returns an **integer** representing the factorial of the specified number `x`.
---
### Code Examples
#### Example 1: Basic Usage
The following example demonstrates how to calculate the factorial of various positive integers:
```python
import math
# Calculate and print the factorial of positive integers
print(math.factorial(9)) # Output: 362880
print(math.factorial(6)) # Output: 720
print(math.factorial(12)) # Output: 479001600
```
**Output:**
```text
362880
720
479001600
```
#### Example 2: Factorial of Zero
By mathematical definition, the factorial of `0` is `1`. The `math.factorial()` method handles this correctly:
```python
import math
# The factorial of 0 is 1
print(math.factorial(0)) # Output: 1
```
**Output:**
```text
1
```
---
### Error Handling & Considerations
When working with `math.factorial()`, you must ensure that the input is a non-negative integer. Passing invalid arguments will result in exceptions.
#### 1. Negative Numbers and Floats (`ValueError`)
If you pass a negative integer or a decimal number, Python will raise a `ValueError`:
```python
import math
try:
# Attempting to pass a negative integer
math.factorial(-5)
except ValueError as e:
print(f"ValueError: {e}")
try:
# Attempting to pass a floating-point number
math.factorial(5.5)
except ValueError as e:
print(f"ValueError: {e}")
```
**Output:**
```text
ValueError: factorial() not defined for negative values
ValueError: factorial() only accepts integral values
```
#### 2. Non-Numeric Types (`TypeError`)
If you pass a non-numeric data type (such as a string), Python will raise a `TypeError`:
```python
import math
try:
# Attempting to pass a string
math.factorial("five")
except TypeError as e:
print(f"TypeError: {e}")
```
**Output:**
```text
TypeError: 'str' object cannot be interpreted as an integer
```
#### 3. Large Numbers and Performance
Python handles arbitrarily large integers automatically. This means `math.factorial()` can calculate factorials for very large numbers without encountering integer overflow issues. However, calculating factorials for extremely large numbers (e.g., `math.factorial(100000)`) can be CPU and memory-intensive.
YouTip