How to Check Whether a Number is Fibonacci or Not in Python

Python program to check whether a given number is a fibonacci number or not; Through this tutorial, i am going to show you how to check whether a given number is fibonacci or not in python.

Fibonacci series of numbers is a series of numbers formed by the addition of the preceding two numbers. The term ‘Fibonacci’ for such a sequence of numbers was coined in the 12th century by Leonardo Fibonacci, who was stumbled by the curious problem of a fictional Rabbit’s breeding process.

In this tutorial, i will write a python program to check whether number is fibonacci or not from user input number; as shown below:

# how to check whether a number is fibonacci or not in python

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 of the above python program to check whether a number is fibonacci or not; as shown below:

Enter an integer number:  5 
Yes, 5 is a Fibonacci number 

Recommended Python Tutorials

Leave a Comment