Test if a Number belongs to the Fibonacci Series

Technology CommunityCategory: Fibonacci SequenceTest if a Number belongs to the Fibonacci Series
VietMX Staff asked 3 years ago

A positive integer ω is a Fibonacci number if and only one of:

  • 2 + 4 and
  • 2 – 4

is a perfect square or a square number.

square number is the result when a number has been multiplied by itself.

Note: it involves squaring a Fibonacci number, frequently resulting in a massive product. There are less than 80 Fibonacci numbers that can even be held in a standard 64-bit integer.

Implementation
bool isFibonacci(int  w)
{
       double X1 = 5 * Math.Pow(w, 2) + 4;
       double X2 = 5 * Math.Pow(w, 2) - 4;

       long X1_sqrt = (long)Math.Sqrt(X1);
       long X2_sqrt = (long)Math.Sqrt(X2);   

       return (X1_sqrt*X1_sqrt == X1) || (X2_sqrt*X2_sqrt == X2) ;
}