GATE CSE
First time here? Checkout the FAQ!
x
+4 votes
130 views
int func(int n) {
    if(n<3)
    return 1;
    else 
    return func(n-1)+func(n-3)+1;
}

How many invocations for calculating func(func(5))

 

asked in Programming by Veteran (43.5k points)   | 130 views
Do we need to save the function calls in a table after calculating or every function call is a fresh call ?
Every call is a fresh - there is no saving in the given code.
Yes, Sir right and also they have not mentioned anything :P

1 Answer

+6 votes
Best answer

$F(5) = F(4) + F(2) + 1$

$F(4) = F(3) + F(1) + 1$

$F(3) = F(2) + F(0) + 1$ 

Hence, Solving all gives $F(5) = 7$ with $3$ distinct invocations.


$F(7) = F(6) + F(4) + 1$

$F(6) = F(5) + F(3) + 1$

$F(5) = F(4) + F(2) + 1$

$F(4) = F(3) + F(1) + 1$

$F(3) = F(2) + F(0) + 1$

And, Solving all gives $F(7) = 17$ with $8$ invocations, assuming there is no saving in the above code.

Or,

 

answered by Veteran (44.9k points)  
edited by
Will add a art work later :)
Yes, Sure :)


Top Users Mar 2017
  1. rude

    4018 Points

  2. sh!va

    2994 Points

  3. Rahul Jain25

    2804 Points

  4. Kapil

    2608 Points

  5. Debashish Deka

    2104 Points

  6. 2018

    1414 Points

  7. Vignesh Sekar

    1336 Points

  8. Bikram

    1218 Points

  9. Akriti sood

    1186 Points

  10. Sanjay Sharma

    1016 Points

Monthly Topper: Rs. 500 gift card

21,446 questions
26,757 answers
60,937 comments
22,954 users