Tutorialspoint
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)
Variables and Data TypesControl StructuresDeloitteSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Define a helper function is_perfect_square that checks if a number is a perfect square.

 Step 2: Define the main function is_fibonacci that takes an integer n.
 Step 3: Handle base cases: return true if n is 0 or 1.
 Step 4: Use the mathematical property: a number is Fibonacci if and only if 5n²+4 or 5n²-4 is a perfect square.
 Step 5: Return true if either condition is satisfied, false otherwise.

Submitted Code :