为什么我的小蟒蛇斐波那契探测器失败了?

Ton*_*hen 1 python algorithm fibonacci

出于某种原因,我必须确定一个大数字是否是斐波纳契数,所以我从互联网复制一些代码并稍微修改它,当它是大输入时似乎运行不好.这是代码:

# python program to check if x is a perfect square

import math

# A utility function that returns true if x is perfect square
def isPerfectSquare(x):
    s = int(math.sqrt(x))
    boo = (s*s == x);
    return boo

# Returns true if n is a Fibinacci Number, else false
def isFibonacci(n):

    # n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
    # is a perferct square
    b = 5*n*n+4;
    c = 5*n*n-4;
    return isPerfectSquare(b) or isPerfectSquare(c)

# A utility function to test above functions

a = int(input("give me the number"));
print(isFibonacci(a))
Run Code Online (Sandbox Code Playgroud)

当我输入时610,它输出true作为计划,但当我输入

"215414832505658809004682396169711233230800418578767753330908886771798637" 
Run Code Online (Sandbox Code Playgroud)

我知道的是我制作的另一个java程序中的第343个斐波纳契数.它输出错误令人惊讶.那是因为数字太大所以会犯错误吗?但我认为python应该能够处理巨大的数字,因为它基于你拥有的内存?是我的程序中的问题还是因为它输入太大?谢谢!

DYZ*_*DYZ 5

你的精确度会下降.为n > 1e45(大约), (n**0.5)**2 != n.尝试使用gmpy2.isqrt()gmpy2.square()来自模块gmpy2- 它们被设计为使用非常大的整数.