3

It is possible to create a fast "give n-th fibonacci number" function as described here. Is there a way to write a isFibonacci(int i) function that perform in O(1)?

I could precalculate values. But the calculation last O(n) and I cant do it for big numbers.

DIBits
  • 483
  • 1
  • 4
  • 13

1 Answers1

4

A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square.

bool isFibonacci(int n) 
{ 
    // n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both 
    // is a perferct square 
    return isPerfectSquare(5*n*n + 4) || 
           isPerfectSquare(5*n*n - 4); 
} 
Phenomenal One
  • 2,501
  • 4
  • 19
  • 29