![]() |
VOOZH | about |
Given a number n, check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ..
Examples :
Input: n = 34
Output: true
Explanation: 34 is one of the numbers of the Fibonacci series.
Input: n = 41
Output: false
Explanation: 41 is not in the numbers of the Fibonacci series.
Table of Content
The idea is to generate Fibonacci numbers one by one starting from
0and1until the generated number becomes greater than or equal ton.
- If the generated Fibonacci number becomes equal to
n, thennis a Fibonacci number.- Otherwise,
nis not a Fibonacci number.
true
Time Complexity: O(log n)
Space Complexity: O(1)
A number
nis a Fibonacci number if either of the following is a perfect square: 5n2 + 4 or 5n2 − 4. So, we calculate both values and check if any one of them is a perfect square. If any one of them is a perfect square, then n is a Fibonacci number.
This is a mathematical property of Fibonacci numbers: 5n2 + 4 or 5n2 − 4.
true
Time Complexity: O(1)
Space Complexity: O(1)