Python Program for How to check if a given number is Fibonacci number?

In this article, we will learn to check whether the given number is a Fibonacci number or not using python.

Fibonacci series

A Fibonacci sequences is sequences of 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .....

The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. 

Fn = F(n-1) +F(n-2)


Program

# Check fibonacci number in python
# import math
import math
# make a function that check the number is perfect square or not
def perfectSquare(x):
s = int(math.sqrt(x))
return s*s == x
# mathe a function that return true for fibonacci series
def is_Fibonacci(n):
# n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both
# is a perfect square
return perfectSquare(5*n*n + 4) or perfectSquare(5*n*n - 4)
# now check the numbers
for i in range(1,15):
if (is_Fibonacci(i) == True):
print (i,"is a Fibonacci Number")
else:
print (i,"is a not Fibonacci Number ")

# Check fibonacci number in python - docodehere.com

Output

1 is a Fibonacci Number 2 is a Fibonacci Number 3 is a Fibonacci Number 4 is a not Fibonacci Number 5 is a Fibonacci Number 6 is a not Fibonacci Number 7 is a not Fibonacci Number 8 is a Fibonacci Number 9 is a not Fibonacci Number 10 is a not Fibonacci Number 11 is a not Fibonacci Number 12 is a not Fibonacci Number 13 is a Fibonacci Number 14 is a not Fibonacci Number
Next Post Previous Post
No Comment
Add Comment
comment url