Python Program for How to check if a given number is Fibonacci number?

Python Program for How to check if a given number is Fibonacci number?

A number is a Fibonacci number if and only if one or both of (5∗n2+4) or (5∗n2−4) is a perfect square.

The above properties can be derived from the properties of Binet's formula.

Steps to determine if a number is a Fibonacci number:

  1. For the given number n, calculate 5×n2+4 and 5×n2−4.
  2. Check if either of them or both are perfect squares.
  3. If yes, n is a Fibonacci number.

Python Program:

def is_perfect_square(num): """Check if a number is a perfect square.""" sqrt = int(num**0.5) return sqrt*sqrt == num def is_fibonacci(n): """Check if a number is a Fibonacci number.""" test1 = 5 * n * n + 4 test2 = 5 * n * n - 4 return is_perfect_square(test1) or is_perfect_square(test2) # Test the function num = 21 if is_fibonacci(num): print(f"{num} is a Fibonacci number.") else: print(f"{num} is not a Fibonacci number.") 

In the program above, we first define a helper function is_perfect_square() to check if a given number is a perfect square. We then use this function in our is_fibonacci() function to check the two conditions (5∗n2+4) and (5∗n2−4).

This method allows us to quickly and efficiently check if a number belongs to the Fibonacci sequence without having to generate the sequence up to that number.


More Tags

screen-recording mockito request-mapping cqrs observablecollection font-awesome message dll regularized merge

More Programming Guides

Other Guides

More Programming Examples