Test if a Number belongs...
Test if a Number belongs...
To determine if a given number belongs to the Fibonacci series, there are several methods you can use. Here are the most common approaches:
One efficient way to check if a number $$ N $$ is a Fibonacci number is by using a mathematical property. A number $$ N $$ is a Fibonacci number if and only if one or both of $$ 5N^2 + 4 $$ or $$ 5N^2 - 4 $$ is a perfect square. This method is based on the properties of Fibonacci numbers and can be implemented as follows:
def is_perfect_square(x):
s = int(math.sqrt(x))
return s * s == x
def is_fibonacci(n):
return is_perfect_square(5 * n * n + 4) or is_perfect_square(5 * n * n - 4)
This method is efficient and has a constant time complexity $$ O(1) $$ for checking if a number is a Fibonacci number[1][2][10].
Another method is to generate Fibonacci numbers iteratively until the generated number is greater than or equal to $$ N $$. If $$ N $$ is found during this process, it is a Fibonacci number.
def is_fibonacci(n):
if n == 0 or n == 1:
return True
a, b = 0, 1
while b < n:
a, b = b, a + b
return b == n
This method has a time complexity of $$ O(\log N) $$ due to the exponential growth of Fibonacci numbers[3][8][10].
Binet's formula provides a direct way to compute the $$ n $$-th Fibonacci number using the golden ratio $$ \phi $$. However, it is more commonly used to generate Fibonacci numbers rather than to check if a number is a Fibonacci number.
import math
def fib_binet(n):
phi = (1 + math.sqrt(5)) / 2
psi = (1 - math.sqrt(5)) / 2
return int((phi**n - psi**n) / math.sqrt(5))
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào