The Wayback Machine - https://web.archive.org/web/20240721114237/https://www.geeksforgeeks.org/tail-recursion-fibonacci/
Open In App

Tail Recursion for Fibonacci

Last Updated : 26 May, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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. 
 

C++




// Tail Recursive Fibonacci
// implementation
#include <iostream>
using namespace std;
 
// A tail recursive function to
// calculate n th fibonacci number
int fib(int n, int a = 0, int b = 1)
{
    if (n == 0)
        return a;
    if (n == 1)
        return b;
    return fib(n - 1, b, a + b);
}
 
// Driver Code
int main()
{
    int n = 9;
    cout << "fib(" << n << ") = "
         << fib(n) << endl;
    return 0;
}


Java




// Tail Recursive
// Fibonacci implementation
 
class GFG
{
    // A tail recursive function to
    // calculate n th fibonacci number
    static int fib(int n, int a, int b )
    {
         
        if (n == 0)
            return a;
        if (n == 1)
            return b;
        return fib(n - 1, b, a + b);
    }
     
    public static void main (String[] args)
    {
        int n = 9;
        System.out.println("fib(" + n +") = "+
                                 fib(n,0,1) );
    }
}


Python3




# A tail recursive function to
# calculate n th fibonacci number
def fib(n, a = 0, b = 1):
    if n == 0:
        return a
    if n == 1:
        return b
    return fib(n - 1, b, a + b);
 
# Driver Code
n = 9;
print("fib("+str(n)+") = "+str(fib(n)))


C#




// C# Program for Tail
// Recursive Fibonacci
using System;
 
class GFG
{
     
    // A tail recursive function to
    // calculate n th fibonacci number
    static int fib(int n, int a , int b )
    {
        if (n == 0)
            return a;
        if (n == 1)
            return b;
        return fib(n - 1, b, a + b);
    }
     
    // Driver Code
    public static void Main ()
    {
        int n = 9;
        Console.Write("fib(" + n +") = " +
                           fib(n, 0, 1) );
    }
}
 
// This code is contributed
// by nitin mittal.


PHP




<?php
// A tail recursive PHP function to
// calculate n th fibonacci number
function fib($n, $a = 0, $b = 1)
{
    if ($n == 0)
        return $a;
    if ($n == 1)
        return $b;
    return fib($n - 1, $b, $a + $b);
}
 
// Driver Code
$n = 9;
echo "fib($n) = " , fib($n);
return 0;
 
// This code is contributed by nitin mittal.
?>


Javascript




<script>
 
// A tail recursive Javascript function to
// calculate n th fibonacci number
 
function fib(n, a = 0, b = 1)
{
    if (n == 0){
        return a;
    }
    if (n == 1){
        return b;
    }
    return fib(n - 1, b, a + b);
}
 
// Driver Code
let n = 9;
document.write(`fib(${n}) =  ${fib(n)}`);
 
 
// This code is contributed by _saurabh_jaiswal.
 
</script>


Output : 
 

fib(9) = 34

Analysis of Algorithm 
 

Time Complexity: O(n)
Auxiliary Space : O(n)

 



Previous Article
Next Article

Similar Reads

Tail vs. Non-Tail Recursion
Tail recursion and Non-tail recursion are two types of recursive functions in computer programming. In this post we will deep dive into what are the major differences between the tail and non-tail recursion. 1) Definition:Tail recursion is defined by having the recursive call as the last operation in the function before returningfunction factorial
3 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Tail recursion to calculate sum of array elements.
Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last statement, the compiler does not need to save the stat
3 min read
Tail Recursion in Python Without Introspection
These are the special type of recursive functions, where the last statement executed inside the function is the call to the function itself. Advantages of implementing Tail Recursive functionIn this concept, the compiler doesn't need to save the stack frame of the function after the tail-recursive call is executed.It uses less memory as compared to
4 min read
What is Tail Recursion
Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. For example the following C++ function print() is tail recursive. C/C++ Code // An example of tail recursive function void print(int n) { if (n &lt; 0
8 min read
Tail Recursion in Python
Tail recursion is a special case of recursion where the recursive call is the last operation in the function. Therefore, the function returns the result of the recursive call directly, without performing any additional computation after the call. In some languages, tail-recursive functions can be transformed into iterative loops to avoid growing th
3 min read
Print Fibonacci Series in reverse order using Recursion
Given an integer N, the task is to print the first N terms of the Fibonacci series in reverse order using Recursion. Examples: Input: N = 5Output: 3 2 1 1 0Explanation: First five terms are - 0 1 1 2 3. Input: N = 10Output: 34 21 13 8 5 3 2 1 1 0 Approach: The idea is to use recursion in a way that keeps calling the same function again till N is gr
3 min read
Check if a M-th fibonacci number divides N-th fibonacci number
Given two numbers M and N, the task is to check if the M-th and N-th Fibonacci numbers perfectly divide each other or not.Examples: Input: M = 3, N = 6 Output: Yes F(3) = 2, F(6) = 8 and F(6) % F(3) = 0 Input: M = 2, N = 9 Output: Yes A naive approach will be to find the N-th and M-th Fibonacci numbers and check if they are perfectly divisible or n
8 min read
Check if sum of Fibonacci elements in an Array is a Fibonacci number or not
Given an array arr[] containing N elements, the task is to check if the sum of Fibonacci elements of the array is a fibonacci number or not.Examples: Input: arr[] = {2, 3, 7, 11} Output: Yes Explanation: As there are two Fibonacci numbers in the array i.e. 2 and 3. So, the sum of Fibonacci numbers is 2 + 3 = 5 and 5 is also a Fibonacci number. Inpu
7 min read
Sorted insert in a doubly linked list with head and tail pointers
A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. The task is to create a doubly linked list by inserting nodes such that list remains in ascending order on printing from left to ri
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg