in Algorithms retagged by
265 views
0 votes
0 votes
int foo(int n){
if(n<3)
return 1;
else
       return (foo(n-1) + foo(n-3) + 1);
}
Let ‘m’ denote the number of invocations of function foo and ‘n’ denote the return value when the function is called as foo(foo(5)). What is the value of
m - n ?
in Algorithms retagged by
265 views

1 Answer

0 votes
0 votes

first we calculate $f(5)$ which comes out to be 7 and took 7 invocations.
While calculating $f(5)$ we noticed $f(4)$ returns value as 5 and takes 5 invocations.
While calculating $f(5)$ we noticed $f(3)$ returns value as 3 and takes 3 invocations.

so till now, we calculated value of $f(5) = 7$ with 7 invocations. 
now, $f(f(5)) = f(7)$



so total number of invocations = 17 + 7 = 24 and value returned is 17.
so m = 24, n = 17 
m-n = 24-17 = 7
 
or 

you can just use the pattern that number of invocation is equal to the  value returned

 

Related questions