gpt4 book ai didi

python - 检查数字是否为斐波那契数的函数?

转载 作者:行者123 更新时间:2023-11-28 20:22:59 25 4
gpt4 key购买 nike

我制作了一个程序,它将多个测试用例作为输入,并且对于每个测试用例,它都需要一个数字作为输入。最后,它会检查您输入的数字是否为斐波那契数列并相应地打印出来。我在我的 PC 上运行它没有问题。但是当我将它上传到 CodeChef.com(我看到这个问题的地方)时,它显示运行时错误。感谢任何帮助,因为我是菜鸟,我的代码可能看起来很长。欢迎进行任何修改。谢谢!

这是我的代码:

def isperfect(n):
import math
if n < 0:
print("No Solution")
return False
else:
test = int(math.sqrt(n))
return test*test == n
test_cases = int(input())
count = 0
store = []
while count < test_cases:
x = int(input())
store.append(x)
count += 1
for each_item in store:
assert isinstance(each_item, int)
s1 = 5*each_item*each_item-4
s2 = 5*each_item*each_item+4
if(isperfect(s1) == True or isperfect(s2) == True):
print("YES")
else:
print("NO")

最佳答案

这是我遇到的最优雅的解决方案:

def is_fibonacci(n):
phi = 0.5 + 0.5 * math.sqrt(5.0)
a = phi * n
return n == 0 or abs(round(a) - a) < 1.0 / n

代码不是我的,是由@sven-marnach 发布的。原帖: check-input-that-belong-to-fibonacci-numbers-in-python

关于python - 检查数字是否为斐波那契数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21800940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com