Ref Math Isqrt
## Python math.isqrt() Method
The `math.isqrt()` method is a built-in function in Python's `math` module that returns the integer square root of a non-negative integer. It computes the square root of a number and rounds the result down to the nearest integer (equivalent to the floor of the exact square root, or $\lfloor\sqrt{x}\rfloor$).
Unlike `math.sqrt()`, which returns a floating-point number, `math.isqrt()` is designed specifically for working with integers and is highly efficient, even for extremely large numbers.
### Availability
* **Python Version:** Introduced in **Python 3.8**.
---
### Syntax
To use the `math.isqrt()` method, you must first import the `math` module:
```python
import math
math.isqrt(x)
```
#### Parameters
| Parameter | Type | Description |
| :--- | :--- | :--- |
| **x** | `int` | Required. A non-negative integer. |
#### Exceptions
* **`ValueError`**: Raised if $x$ is a negative number (i.e., $x < 0$).
* **`TypeError`**: Raised if $x$ is not an integer (e.g., a float, string, or other non-integer type).
#### Return Value
* **`int`**: Returns the integer square root of $x$. This is the greatest integer $a$ such that $a^2 \le x$.
---
### Code Examples
#### Example 1: Basic Usage and Comparison with `math.sqrt()`
The following example demonstrates how `math.isqrt()` differs from `math.sqrt()`. While `math.sqrt()` returns a float, `math.isqrt()` returns a truncated integer.
```python
import math
# Calculate the standard square root (returns float)
print("--- math.sqrt() Results ---")
print(math.sqrt(10)) # Output: 3.1622776601683795
print(math.sqrt(12)) # Output: 3.4641016151377544
print(math.sqrt(68)) # Output: 8.246211251235321
print(math.sqrt(100)) # Output: 10.0
print("\n--- math.isqrt() Results ---")
# Calculate the integer square root (rounds down to the nearest integer)
print(math.isqrt(10)) # Output: 3
print(math.isqrt(12)) # Output: 3
print(math.isqrt(68)) # Output: 8
print(math.isqrt(100)) # Output: 10
```
**Output:**
```text
--- math.sqrt() Results ---
3.1622776601683795
3.4641016151377544
8.246211251235321
10.0
--- math.isqrt() Results ---
3
3
8
10
```
---
#### Example 2: Handling Large Integers
One of the primary advantages of `math.isqrt()` is its ability to handle arbitrarily large integers without losing precision due to floating-point limitations.
```python
import math
# A very large integer
large_num = 10**40
# math.isqrt() handles this precisely and returns an integer
result = math.isqrt(large_num)
print(f"Integer square root: {result}")
print(f"Type of result: {type(result)}")
```
**Output:**
```text
Integer square root: 100000000000000000000
Type of result:
```
---
#### Example 3: Error Handling
If you pass a negative number or an invalid data type, Python will raise an exception.
```python
import math
# 1. Passing a negative number raises ValueError
try:
math.isqrt(-9)
except ValueError as e:
print(f"ValueError: {e}")
# 2. Passing a non-integer type raises TypeError
try:
math.isqrt(9.5)
except TypeError as e:
print(f"TypeError: {e}")
```
**Output:**
```text
ValueError: isqrt() argument must be nonnegative
TypeError: 'float' object cannot be interpreted as an integer
```
---
### Considerations & Best Practices
1. **Precision with Large Numbers**: Standard floats in Python have 53 bits of precision. If you use `int(math.sqrt(x))` on a very large integer, you may get an incorrect result due to rounding errors during the float conversion. Always use `math.isqrt(x)` when working with large integers to guarantee exact precision.
2. **Performance**: `math.isqrt()` is implemented in C and optimized for speed. It is much faster than implementing integer square root algorithms (like Newton's method) manually in pure Python.
3. **Strict Type Checking**: Unlike many other math functions, `math.isqrt()` does not implicitly convert floats to integers. Passing a float like `9.0` will result in a `TypeError`. You must explicitly pass an `int`.
YouTip