“Python如何(以及为什么)“精确地计算完美平方的平方根”?

2024-10-03 06:24:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个令人惊奇的数字,这个数字是Loeschian吗整体而言:

Python, 49 bytes

lambda n:0in[(n-3*i*i+0j)**.5%1for i in range(n)]

Uses the equivalent quadratic form given on OEIS of n == 3*i*i+j*j. Check whether n-3*i*i is a perfect square for any i by taking its square root and checking if it's an integer, i.e. equals 0 modulo 1. Note that Python computes square roots of perfect squares exactly, without floating point error. The +0j makes it a complex number to avoid an error on the square root of a negative.

Python是如何做到这一点的?**.5是否“检测”到某个给定的数字不知何故是一个完美的正方形?这是否仅适用于整数输入,还是也适用于某些大小的浮点

我还添加了一个插入语为什么<对问题的回答;这是程序员依赖的东西吗?是为了速度吗?它有成本吗


Tags: ofthelambdainanbytesonrange
1条回答
网友
1楼 · 发布于 2024-10-03 06:24:42

您可以查看源代码here。他们描述了用于计算非负整数(近似)平方根的算法,并表明对于完美平方,该算法给出了精确答案。代码是C,但它们将代码翻译成Python:

def isqrt(n):
    """
    Return the integer part of the square root of the input.
    """
    n = operator.index(n)
    if n < 0:
        raise ValueError("isqrt() argument must be nonnegative")
    if n == 0:
        return 0
    c = (n.bit_length() - 1) // 2
    a = 1
    d = 0
    for s in reversed(range(c.bit_length())):
        # Loop invariant: (a-1)**2 < (n >> 2*(c - d)) < (a+1)**2
        e = d
        d = c >> s
        a = (a << d - e - 1) + (n >> 2*c - e - d + 1) // a
    return a - (a*a > n)

我假设,但还没有检查,当在运行时计算电源时,Python首先检查1。基数是一个非负整数,2。指数正好是0.5,如果两者都成立,那么它将调用我上面链接的代码

相关问题 更多 >