Wednesday, November 25, 2009

C source code to check IsFibonacci()

As promised, here is code to check for any given number belongs to Fibonacci series or not?

/*
Theorem:
A positive integer n is Fibonacci if, and only if, (5*n*n+4) OR (5*n*n+4) is a perfect square.
*/

bool IsFibonacci(int n)
{
    // Calculate criteria expressions
    int criteria[2];
    criteria[0] = 5 * n * n + 4;
    criteria[1] = 5 * n * n - 4;

    // Determine whether one of them is a perfect square
    int sqr[2];
    sqr[0] = sqrt(criteria[0]);
    sqr[1] = sqrt(criteria[1]);

    // Return result
    return ((pow(sqr[0], 2) == criteria[0]) || (pow(sqr[1], 2) == criteria[1]));
}
Comments and suggestions are always welcome!

Cheers!
Rajendra

No comments: