FibonacciGenerator


This is a simple drop-in function that will return the next number in the Fibonacci sequence every time you call it.  specialcase is used to properly generate the first two numbers, 0 and 1, before dropping into the well known next = current + previous pattern.  num1 and num2 are the previous and current numbers in the sequence, and since they're "static," their values will be retained between calls.

Note that return specialcase++; returns the value of specialcase before incrementing it, otherwise it would return 1, 2 instead of the needed 0, 1.

 

Code:

int genfib() {

    static int num1=0, num2=1, specialcase = 0;

    if (specialcase < 2) {

        return specialcase++;

    }

    int num3 = num1 + num2;

    num1 = num2;

    num2 = num3;

    return num3;

}

 

Usage:

while (1) {

     printf("%d\n", genfib());

}

 

The expected output is:

0

1

1

2

3

5

8

--- etc ---

 


Extensions:

There is no method to reset fibgen if you need to start over, but encapsulating the variables num1, num2, and specialcase in a struct would be trivial.  Then pass the pointer to this struct to fibgen every time you call it.

 

int fibgen() could be easily rewritten to use 64 bit variables if a longer sequence is needed for some reason.  Just change the function declaration, num1, num2, and num3 to uint64_t.

 


Sources:

http://en.wikipedia.org/wiki/Fibonacci_number