Search code examples
javarecursionfibonaccitail-recursionfactorial

tail recursive version for Fibonacci-like function


I am having trouble understanding the concept of tail recursion, I want to make a tail recursive version for Fibonacci-like function, p1= n-3 , p2= n-2, fx( p1 ) + fx( p2 ) and so far this is what I came up with but I don't know if it's a correct approach, can someone help me out, any help would be appreciated p1= n-3 , p2= n-2 Long doCalc( long n ) { return n == 0 ? 0 : ( n == 1 ? 1 : ( n == 2 ? 1 : (make( p1 ) + make( p2 )) ) ); }

the code outputs the correct result

but when i implement the tail recursive , my approach was split and conquer, but it's not working and the output are wrong

Long factor3(Long n, Long a)
{
    if( n == 0){
        return 0l;
    } else if( n == 1 || n == 2) {
        return a;
    }

    return factor3(p1, n + a);
}

Long factor2(Long n, Long a)
{
    if( n == 0){
        return 0l;
    } else if( n == 1 || n == 2) {
        return a;
    }

    return factor2(p2, n + a);
}

Solution

  • Sadly, I do not have enough reputation to comment, but to answer your question:

    First of all, this link really helps to understand how to achieve the solution.

    It's pretty much: Since you start with (a,b,c) = (0,1,1) and you want to derive the next number by adding the second and third last, your next number (hypothetically d) would be a+b

    so (a,b,c,d) = (a,b,c,a+b)

    Which means when you look at the next iteration, you "shift" everything left and your next call will be (b,c,a+b) as stated by Andrey