In Fibonacci Sequence, every previous two numbers gives the next number.
the first 10 Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 35
In this python Program we will see how to test if a number given by user belongs to the Fibonacci sequence.
If the given number is n then any of 5n*n + 4 or 5n*n – 4 or both should be a perfect square to be a Fibonacci number.
Python Code:
import math
def CheckPerfect(x):
i = int(math.sqrt(x))
return (x == i*i)
def CheckFibo(n):
if(CheckPerfect(5*n*n + 4) or CheckPerfect(5*n*n - 4)):
print("Fibonacci")
else:
print("Not Fibonacci")
CheckFibo(89) #this returns true, 89 is Fibonacci
you can suggest better algorithm for this in the comments!
You can take this Python Quiz