Checking Fibonacci number in Python: Here, we will realize whether a given number is a Fibonacci number or not utilizing Python program?
Given a number and we need to check whether it is a Fibonacci number or not in Python?
Checking Fibonacci number
Consider the given Fibonacci arrangement with an initial not many terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, etc…
There is a well-known recipe to check whether a given number is a Fibonacci number or not? (5n2 + 4) or (5n2 – 4)
In the event that the aftereffect of this recipe is an ideal square, at that point, the number will be a Fibonacci number.
Example:
Input:
num = 13
Output:
Yes, 13 is a Fibonacci number
Input:
num = 143
Output:
No, 144 is not a Fibonacci number
Python program to check Fibonacci number
# python program to check if given
# number is a Fibonacci number
import math
# function to check perferct square
def checkPerfectSquare(n):
sqrt = int(math.sqrt(n))
if pow(sqrt, 2) == n:
return True
else:
return False
# function to check Fibonacci number
def isFibonacciNumber(n):
res1 = 5 * n * n + 4
res2 = 5 * n * n - 4
if checkPerfectSquare(res1) or checkPerfectSquare(res2):
return True
else:
return False
# main code
num = int(input("Enter an integer number: "))
# checking
if isFibonacciNumber(num):
print ("Yes,", num, "is a Fibonacci number")
else:
print ("No,", num, "is not a Fibonacci number")
Output:
First run:
Enter an integer number: 13
Yes, 13 is a Fibonacci number
Second run:
Enter an integer number: 144
Yes, 144 is a Fibonacci number
Third run:
Enter an integer number: 143
No, 143 is not a Fibonacci number