math.isqrt Keeps Integer Square Roots Exact
math.sqrt converts to float first and loses precision past 2**53, while math.isqrt stays exact on arbitrarily large integers and detects perfect squares.
Code
import math
# float 平方根在 2**53 之后开始丢精度;isqrt 始终精确
n = (10**17 + 1) ** 2
float_root = int(math.sqrt(n))
exact_root = math.isqrt(n)
print("n =", n)
print("int(sqrt) =", float_root)
print("math.isqrt =", exact_root)
print("float loses the +1:", float_root != exact_root)
# 判别完全平方数:先取整再平方验证,避免浮点比较
def is_perfect_square(value: int) -> bool:
if value < 0:
return False
root = math.isqrt(value)
return root * root == value
for candidate in [10**16, 10**16 + 1, 0, 2]:
print(candidate, "->", is_perfect_square(candidate))Output
Captured from a sandboxed run of this snippet in the build pipeline.
n = 10000000000000000200000000000000001
int(sqrt) = 100000000000000000
math.isqrt = 100000000000000001
float loses the +1: True
10000000000000000 -> True
10000000000000001 -> False
0 -> True
2 -> FalseInside the snippet
math.isqrt Keeps Integer Square Roots Exact is built around the function is_perfect_square.
The file repeats itself only inside for candidate in [10**16, 10**16 + 1, 0, 2].
Using it
Entry signature: def is_perfect_square(value: int) -> bool
The demo output is labeled (math.isqrt =, float loses the +1:), so every printed line maps back to its originating operation.
Import is_perfect_square from the file and call it — the rest of the code is implementation detail.
Key statements
def is_perfect_square(value: int) -> bool:
if value < 0:
return False
root = math.isqrt(value)
return root * root == value
Interactive Tools for This Topic
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `math`. The file defines `is_perfect_square` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.