## Wednesday, July 15, 2015

### Checking a number as it is Fibonacci number or not

Hello Friends, today I want to give you a basic information that is very useful in letting know whether the number is a fibonacci number just by simple formula.

Here it goes,

Let us suppose we have to check whether the number n is a fibonacci number or not, then the condition 5n^2 + 4 or 5n^2 - 4 should be a perfect square.

``` // A utility function that returns true if x is perfect square
bool isPerfectSquare(int x)
{
int s = sqrt(x);
return (s*s == x);
}
// Returns true if n is a Fibinacci Number, else false
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);
}
int main()
{
for (int i = 1; i <= 10; i++)
isFibonacci(i)? cout << i << " is a Fibonacci Number \n":
cout << i << " is a not Fibonacci Number \n" ;
return 0;
}
```

Now once you pass the number to the function it will tell you whether or not the number is a part of fibonacci series or not.

Thanks