How to test if a Number belongs to the Fibonacci Series in C#

To test if a number belongs to the Fibonacci series in C#, you can use the following approach:

  1. Check if the number is a perfect square:
    • A number belongs to the Fibonacci series if and only if (5 * n^2 + 4) or (5 * n^2 - 4) is a perfect square.
    • You can use the Math.Sqrt() function to check if a number is a perfect square by comparing its square root with the integer value of the square root.
  2. Implement a method to test if a number is in the Fibonacci series:
    • Create a method, let’s call it IsFibonacci(), that takes an integer as input and returns a boolean indicating whether the number belongs to the Fibonacci series.
    • In the method, check if (5 * n^2 + 4) or (5 * n^2 - 4) is a perfect square using the above approach.
    • Return true if either of the two conditions is met; otherwise, return false.

Here’s an example implementation of the IsFibonacci() method:

public static bool IsFibonacci(int number)
    int term1 = 5 * number * number + 4;
    int term2 = 5 * number * number - 4;

    return IsPerfectSquare(term1) || IsPerfectSquare(term2);

private static bool IsPerfectSquare(int number)
    int sqrt = (int)Math.Sqrt(number);
    return sqrt * sqrt == number;

You can then use the IsFibonacci() method to test if a given number belongs to the Fibonacci series. For example:

int number = 8;
bool isFibonacci = IsFibonacci(number);

Console.WriteLine($"The number {number} {(isFibonacci ? "belongs to" : "does not belong to")} the Fibonacci series.");

In this example, the number 8 is tested using the IsFibonacci() method, and the result is displayed in the console.

Please note that this approach works for integers within the range supported by the int data type. If you need to test larger numbers, you may need to use a different approach that handles big integers or consider performance optimizations.

error: Content is protected !!