Home » Python » Python programs

Python program to check whether a given number is a Fibonacci number or not

Checking Fibonacci number in Python: Here, we are going to learn whether a given number is a Fibonacci number or not using Python program?
Submitted by IncludeHelp, on May 26, 2019

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

Checking Fibonacci number

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 number 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.

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.