You are given an integer, all you have to do is to find whether this number is a Fibonacci number or not.
Fn is said to be a Fibonacci sequence such that each number in Fn is the sum of its two preceding numbers, starting with 0 and 1.
Fn = F(n-1) + F(n-2)
fn is said to be a Fibonacci number if it is a part of the Fn/Fibonacci sequence.
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain a single integer ‘N’ which denotes the given number that has to check whether it is a Fibonacci number or not.
Output Format:
For each test case, print the “YES” if the number is a Fibonacci number. Otherwise, print “NO”.
Output for every test case will be printed in a separate line.
Note:
You don’t need to print anything; It has already been taken care of.
1 <= T <= 100
0 <= N <= 100000
Where ‘T’ is the number of test cases.
Where 'N' is the given number.
Time limit: 1 sec
2
5
6
YES
NO
In the first test case, 5 is a Fibonacci number.
In the second test case, 6 is not a Fibonacci number.
2
1
0
YES
YES
In the first test case, 1 is a Fibonacci number.
In the second test case, 0 is a Fibonacci number.
Can you think of going through each Fibonacci number from starting?
The basic idea is to keep generating Fibonacci numbers until we find a number equal to the given number or the generated number becomes greater than the given number. If the generated number is equal to the given number then it means the given number is a Fibonacci number. Otherwise, it is not a Fibonacci number.
The steps are as follows:
O(log(N)), where ‘N’ is the given number.
We know that, nth Fibonacci number is given as [ { (sqrt(5) + 1) / 2 } ^ n ] / sqrt(5). Now, lets assume that the given number is a kth Fibonacci number or kth Fibonacci number is just greater than the ‘N’. So,
[ { (sqrt(5) + 1) / 2 } ^ k ] / sqrt(5) <= N
If we calculate the value of k from here then we get,
k <= log [ (2 * sqrt(5) * n - sqrt(5) - 1) / 2 ]
so the overall time complexity will be O(log(N)).
O(1).
We are not using any extra space and so, the overall space complexity will be O(1).