如何找到最近的斐波那契数列编号?
发布于 2021-01-29 18:19:06
我的下一步是,如果输入不在斐波那契数列中,则程序必须给出一个输出,该数字的序列中的数字最接近输入。我不知道如何进行,有人可以帮助我吗?
def fibs():
a,b = 0,1
yield a
yield b
while True:
a,b = b,a+b
yield b
n = int(input("please, enter a number: "))
for fib in fibs():
if n == fib:
print("Yes! Your number is a Fibonacci number!")
break
if fib > n:
print("No! Your number is not a Fibonacci number!")
break
关注者
0
被浏览
212
1 个回答
-
为什么这种方法行之有效:
这是一种不需要先前计算的方法,因此对于 性能 以及在检查非常大的数字时非常有用。
该程序:
from math import * n = int(input("Enter a number:")) if sqrt(5*n**2+4)%1==0 or sqrt(5*n**2-4)%1==0: print("Your number is a Fibonacci number!") else: print("Your number is not a Fibonacci number.") c = 0 while 1: c += 1 if sqrt(5*(n+c)**2+4)%1==0 or sqrt(5*(n+c)**2-4)%1==0: print("%s is the closest Fibonacci number to your entry." % str(n+c)) break if sqrt(5*(n-c)**2+4)%1==0 or sqrt(5*(n-c)**2-4)%1==0: print("%s is the closest Fibonacci number to your entry." % str(n-c)) break
说明:
如果(5 * n ^ 2 + 4)或(5 * n ^ 2-4 – 4)是一个理想平方,则n是斐波那契数。
程序输入/输出
Enter a number: 9999999999 Your number is not a Fibonacci number. 9999816735 is the closest Fibonacci number to your entry. Enter a number: 9999816735 Your number is a Fibonacci number!