实现说明
底层就是函数 is_perfect_square。
在这里做循环的是 for candidate in [10**16, 10**16 + 1, 0, 2]。
使用要点
- 跑完文件,输出里会留下标记——
math.isqrt =、float loses the +1:。 - 调用方只需要
is_perfect_square——其余都是内部实现。
常见问题
这份代码可以原样复制进项目使用吗?
可以。粘进去就能运行,中间没有包管理器的事。 全部导入都来自标准库:math。 文件在加载时定义 is_perfect_square。
主要签名是 def is_perfect_square(value: int) -> bool
核心语句
def is_perfect_square(value: int) -> bool:
if value < 0:
return False
root = math.isqrt(value)
return root * root == value
代码示例
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))