In Fibonacci Sequence

  • Write a method that determines whether or not a input number n is in the fibonacci sequence.

  • Approach: Produce the fib sequence dynamically, bottom up, and simply check stop once it is found, or exceeds the given number.

// 1,1,2,3,5,8,13, ... 

bool is_in_fib_sequence(int n)
{
    if (n == 1) return true;
    else if (n < 0) return false;
    int start = 1;
    int next = 1;

    int temp, fib_number;
    temp = fib_number = 0;

    while (1)
    {
        fib_number = start + next;

        if (n == fib_number) return true;
        else if (fib_number > n) return false;

        temp = next;
        next = fib_number;
        start = temp;
    }
}

int main()
{
    cout << boolalpha << is_in_fib_sequence(1) << endl;
    cout << boolalpha << is_in_fib_sequence(5) << endl;
    cout << boolalpha << is_in_fib_sequence(6765) << endl;
    cout << boolalpha << is_in_fib_sequence(50) << endl;
}

Last updated