user7043763 - 2 months ago 11

Python Question

My next step is if the input is not in the Fibonacci Series, the program has to give an output with a number which is in the series that is nearest to the input. I do not know how to proceed, can anyone help me?

`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

Answer

This is a way that does not require previous computation, so is fantastic for **performance** and such when checking very large numbers.

```
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
```

If (5*n^2 + 4) or (5*n^2 – 4) is a perfect square, then n is a Fibonacci number.

```
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!
```