Check a given number is a Fibonacci term or not in Python

In this tutorial, we will learn how to check whether a given number is a Fibonacci term or not using Python program? By IncludeHelp Last updated : August 29, 2023

Problem statement

Given a number and we have to check whether it is a Fibonacci number or not in Python?

Example

Input: 
num = 13
Output:
Yes, 13 is a Fibonacci number

Input: 
num = 143
Output:
No, 143 is not a Fibonacci number

Checking Number is a Fibonacci Term

Consider the given Fibonacci series with a first few terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, and so on...

There is a popular formula to check whether a given number is a Fibonacci term or not,

(5*n2 + 4) or (5*n2 – 4)

If the result of this formula is a perfect square then the number will be a Fibonacci number.

Algorithm

  • Input a number.
  • Find the result of the (5*n2 + 4) and (5*n2 - 4).
  • Pass the result of these expressions in a function to check whether it is a perfect square or not.
  • Now, if the perfect square of any of these results is TRUE.
  • Then, the given number will be a Fibonacci term.

Python program to check given number is a Fibonacci term

# 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

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.