F Sharp Programming/Solutions/Recursion

Faster Fib Function
The following function calculates the nth number in the Fibonacci sequence:

The function above is neither tail-recursive nor particularly efficient with a computational complexity O(2n). The tail-recursive form of this function has a computational complexity of O(n). Re-write the function above so that its tail recursive.

You can verify the correctness of your function using the following: fib(0) = 0 fib(1) = 1 fib(2) = 1 fib(3) = 2 fib(4) = 3 fib(5) = 5 fib(10) = 55 fib(100) = 354224848179261915075

Solution
Examine the first 10 numbers in the Fibonacci sequence: n: fib(n) - 0: 0 1: 1 2: 1 3: 2 4: 3 5: 5 6: 8 7: 13 8: 21 9: 34 10: 55

Each number in the sequence is the sum of two numbers above it. If we hold the values of the previous two fib numbers in accumulating parameters, then we can calculate then next fib number very easily.

The accumulator variables  and   correspond to   and   respectively.

We can test this function in fsi: