How to Check if a Given Number is Fibonacci Number in Python?

How to Check if a Given Number is Fibonacci Number in Python?

We all know about the Fibonacci series. In this tutorial, instead of printing the Fibonacci sequence, we want to check whether the given number is a Fibonacci number or not.

This question was asked in many Python interviews.

Solution

Fibonacci is infinite series. It means it can have as many numbers as our system supports ūüėČ .

So getting complete Faboncaci series and checking the given number whether it is present in the series or not, is not possible.

We can simply check each element while generating the Fibonacci element until we find the given number or Fibonacci number is greater than a given number.

Python Code

Let’s write Python code to solve this problem.

Prerequiste:

def is_fib_number(num):
    a = 0
    b = 1
    while b<num:
        c = a+b
        a = b
        b = c
    if b==num or a==num:
        return True
    if b > num:
        return False

num = 13
if is_fib_number(num):
    print(f"{num} is a fibonacci number.")
else:
    print(f"{num} is not a fibonacci number.")

Output:

13 is a fibonacci number.

We are formatting the outpout using Python string formatting. Rest of the code is self explanatiory. If you have any doubt, let me know in the comment.

This is all about writing code to check if a given number is Fibonacci number in Python. To enahnce your coding skills, check interview coding questions for practice.

Leave a Reply

Your email address will not be published. Required fields are marked *