![]() |
VOOZH | about |
Write a tail recursive function for calculating the n-th Fibonacci number.
Examples :
Input : n = 4 Output : fib(4) = 3 Input : n = 9 Output : fib(9) = 34
Prerequisites : Tail Recursion, Fibonacci numbers
A recursive function is tail recursive when the recursive call is the last thing executed by the function.
Writing a tail recursion is little tricky. To get the correct intuition, we first look at the iterative approach of calculating the n-th Fibonacci number.
int fib(int n)
{
int a = 0, b = 1, c, i;
if (n == 0)
return a;
for (i = 2; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return b;
}
Here there are three possibilities related to n :-
n == 0
n == 1
n > 1
First two are trivial. We focus on discussion of the case when n > 1.
In our iterative approach for n > 1,
We start with
a = 0 b = 1
For n-1 times we repeat following for ordered pair (a,b)
Though we used c in actual iterative approach, but the main aim was as below :-
(a, b) = (b, a+b)
We finally return b after n-1 iterations.
Hence we repeat the same thing this time with the recursive approach. We set the default values
a = 0 b = 1
Here we'll recursively call the same function n-1 times and correspondingly change the values of a and b.
Finally, return b.
If its case of n == 0 OR n == 1, we need not worry much!
Here is implementation of tail recursive fibonacci code.
Output :
fib(9) = 34
Analysis of Algorithm
Time Complexity: O(n) Auxiliary Space : O(n)