
Problem
Solution
Submissions
Checking Fibonacci Number
Certification: Basic Level
Accuracy: 100%
Submissions: 4
Points: 10
Write a C++ program that determines whether a given positive integer is a Fibonacci number or not.
Example 1
- Input: n = 8
- Output: true
- Explanation:
- Step 1: A number is a Fibonacci number if and only if one of (5n² + 4) or (5n² - 4) is a perfect square.
- Step 2: For n = 8, calculate 5n² + 4 = 5×8² + 4 = 5×64 + 4 = 320 + 4 = 324.
- Step 3: Check if 324 is a perfect square. √324 = 18, which is an integer.
- Step 4: Since one of the conditions is met, 8 is a Fibonacci number.
Example 2
- Input: n = 7
- Output: false
- Explanation:
- Step 1: A number is a Fibonacci number if and only if one of (5n² + 4) or (5n² - 4) is a perfect square.
- Step 2: For n = 7, calculate 5n² + 4 = 5×7² + 4 = 5×49 + 4 = 245 + 4 = 249.
- Step 3: Check if 249 is a perfect square. √249 ≈ 15.78, which is not an integer.
- Step 4: Calculate 5n² - 4 = 5×49 - 4 = 245 - 4 = 241.
- Step 5: Check if 241 is a perfect square. √241 ≈ 15.52, which is not an integer.
- Step 6: Since neither condition is met, 7 is not a Fibonacci number.
Constraints
- 0 ≤ n ≤ 10^9
- Input is a non-negative integer
- Time Complexity: O(log n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- A number is a Fibonacci number if and only if either (5 * n^2 + 4) or (5 * n^2 - 4) is a perfect square
- Use the property that the sequence of Fibonacci numbers grows exponentially
- Check if the number is 0 or 1 separately as they are special cases
- Implement a function to check if a number is a perfect square