ShareThis

Monday, August 13, 2012

[java] Is Number in Fibonacci Sequence Code

Found this code on StackOverflow. This is a very simple iterative solution to see if a given long value "n" is a part of the fibonacci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, etc...

int isFib (long n)
{
    int pos = 2;
    long last = 1;
    long current = 1;
    long temp;

    while (current < n)
    {
        temp = last;
        last = current;
        current = current + temp;
        pos++;
    }

    if (current == n)
        return pos;
    else
        return 0;
}

0 comments:

Post a Comment