Program to check given number is a Fibonacci term in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number say n. We have to check whether n is present in Fibonacci sequence or not. As we know in Fibonacci sequence f(i) = f(i-1) + f(i-2) for each i from 2 to n, and f(0) = 0, f(1) = 1.

So, if the input is like n = 13, then the output will be True, as some terms in Fibonacci sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, so 34 is present.

To solve this, we will follow these steps −

  • phi := 0.5 + 0.5 * square root of(5.0)
  • a := phi * n
  • return true when n is same as 0 or a is an integer

Example

Let us see the following implementation to get better understanding −

from math import sqrt
def solve(n):
   phi = 0.5 + 0.5 * 5.0**0.5
   a = phi * n
   return n == 0 or abs(round(a) - a) < 1.0 / n

n = 13
print(solve(n))

Input

13

Output

True
raja
Updated on 11-Oct-2021 07:20:43

Advertisements