Home > Back-end >  Clarification on tail recursive methods
Clarification on tail recursive methods

Time:06-15

Is the following method tail-recursive?

I believe that it is not tail recursive because it relies on the previous results and so needs a stack frame, am I correct to state this?

public int[] fib(int n)
{
    
    if(n <= 1){
        return (new int[]{n,0});
    }
    else{
        int[] F = fib(n-1);
        return (new int[]{F[0]  F[1], F[0]});
    }
}

CodePudding user response:

You are correct: It is not tail recursive because the last line is not of the form

return funcName(args);

CodePudding user response:

Yes, you are correct, since it does not end with a call to itself of the form of

return fib(somevalue);

To convert it into a tail-recursive version you could do something like

// 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) );
    }
}

Code taken from https://www.geeksforgeeks.org/tail-recursion-fibonacci/

  • Related