这是一个令人惊奇的数字,这个数字是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 whethern-3*i*i
is a perfect square for anyi
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
是否“检测”到某个给定的数字不知何故是一个完美的正方形?这是否仅适用于整数输入,还是也适用于某些大小的浮点
我还添加了一个插入语为什么<对问题的回答;这是程序员依赖的东西吗?是为了速度吗?它有成本吗
您可以查看源代码here。他们描述了用于计算非负整数(近似)平方根的算法,并表明对于完美平方,该算法给出了精确答案。代码是C,但它们将代码翻译成Python:
我假设,但还没有检查,当在运行时计算电源时,Python首先检查1。基数是一个非负整数,2。指数正好是
0.5
,如果两者都成立,那么它将调用我上面链接的代码相关问题 更多 >
编程相关推荐