Program to check whether the given number is Fibonacci number or not in Python

Introduction

In the previous article, we have understood the mathematical expression to find nth Fibonacci number. In this article, we will learn to write python code to check whether the given number is Fibonacci number or not. The number is said to be a Fibonacci number if the expression (5*n*n + 4) or (5*n*n – 4) or both is a perfect square. The first few Fibonacci numbers are:

0, 1, 1, 2, 3, 5, 8, 13, …….

Program to check whether the given number is Fibonacci number or not

 

Program

import math
n = int(input("Please enter the integer value to check Fibonacci number: "))


def check_perfect_square(m):
    n = int(math.sqrt(m))
    return n*n == m
   
def check_fibo(m):
    return check_perfect_square(5*m*m + 4) or check_perfect_square(5*m*m - 4)
if(check_fibo(n) == True):
    print( n," is Fibonacci number")
else:
    print( n," is not Fibnacci number")

Output

Program to check whether the given number is Fibonacci number or not Output

Explanation

In the above python code, we have created a variable n, function check_perfect_square()  and check_fibo().The function check_perfect_square() returns the value True if the given number is perfect square and the integer value is passed to function check_fibo(). If the expression (5*m*m + 4) or (5*m*m – 4) holds true for given input then the number is a Fibonacci number.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.