Python Glossary Русский

Python 3.8+Numbers & mathfunction

math.isqrt

roots/powers

Integer square root: the floor of √n (exact integer arithmetic).

Syntax

math.isqrt(...)

The usual int(n ** 0.5) or int(math.sqrt(n)) routes through float and starts being off by one for large values (roughly past 2**52); isqrt stays in integer arithmetic and is exact for any n. It takes integers only: a float raises TypeError and a negative argument raises ValueError rather than returning nan. Available since Python 3.8.

Examples

import math
print(math.isqrt(17))   # → 4
print(math.isqrt(16))   # → 4
n = 49; print(math.isqrt(n) ** 2 == n)   # → True
n = 10 ** 18 - 1; print(math.isqrt(n))   # → 999999999
print(int(math.sqrt(n)))   # → 1000000000
print(math.isqrt(-1))   # → ValueError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy