我的下一步是如果输入不在Fibonacci系列中,程序必须给出一个输出,其中的数字在最接近输入的系列中.我不知道怎么办,有人能帮助我吗?
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
解决方法:
为什么这种方法效果很好:
这是一种不需要先前计算的方法,因此在检查非常大的数字时非常出色.
该程序:
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)是完美的平方,则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!