How to Check if a Given Number is Fibonacci number - Python
Fibonacci numbers are part of a famous sequence where each number is the sum of the two preceding ones, i.e. F(n) = F(n-1) + F(n-2). The sequence starts as:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Notice that every number is equal to the sum of its previous 2 numbers.
In this article, we will learn how to identify if a given number belongs to the Fibonacci series or not.
Examples :
Input: 8
Output: YesInput: 31
Output: No
Fibonacci Number Check Using a Mathematical Property
A number n is a Fibonacci number if and only if one or both of (5*n² + 4) or (5*n² – 4) is a perfect square.
The above mathematical expression is derived from the closed-form expression of Fibonacci numbers (Binet’s Formula) and some number theory. It’s fast and doesn’t require generating the Fibonacci sequence. Let's look at the code implementation in Python:
Output
Explanation:
1. is_perfect_sq(x):
- Calculates the integer square root of x.
- Returns True if x is a perfect square, else False.
2. is_fibonacci(n):
- Applies the mathematical identity:
- A number n is Fibonacci if 5*n² + 4 or 5*n² – 4 is a perfect square.
- Calls is_perfect_sq() on both expressions to check this.
3. Loop: Iterates through numbers 1 to 6 and prints whether each number is a Fibonacci number based on the result from is_fibonacci().
๐ Follow Ashok IT School for daily Python logic programs
Comments
Post a Comment