N
nthrgeek
Consider the following code snippet:
int find_fib(int N)
{
assert(N>0);
int f1 = 1;
int f2 = 1;
if(N<2) return 1;
return (find_fib(N-1) + find_fib(N-2));
}
Given that find_fib is called from main with N as 25,how many total
calls
are made to find_fib ? (We can't modify the find_fib)
Manually we can derive this:
Let f(n) be the number of calls made to calculate fib(n).
* If n < 2 then f(n) = 1.
* Otherwise, f(n) = 1 + f(n - 1) + f(n - 2).
So, f is at least O(fib(n)). In fact, f(n) is 2 * fib(n) - 1. We show
this by induction:
* Base cases (n < 2, that is, n = 0 or n = 1):
o f(n) = 1 = 2 * 1 - 1 = 2 * fib(n) - 1.
* Induction step (n >= 2):
o f(n + 1) = f(n) + f(n - 1) + 1
o f(n + 1) = 2 * fib(n) - 1 + 2 * fib(n - 1) - 1 + 1
o f(n + 1) = 2 * fib(n + 1) - 1
Modifying the find_fib by including a counter variable,I computed:
fib(25) =121393
Number of times called : 242785
int find_fib(int N)
{
assert(N>0);
int f1 = 1;
int f2 = 1;
if(N<2) return 1;
return (find_fib(N-1) + find_fib(N-2));
}
Given that find_fib is called from main with N as 25,how many total
calls
are made to find_fib ? (We can't modify the find_fib)
Manually we can derive this:
Let f(n) be the number of calls made to calculate fib(n).
* If n < 2 then f(n) = 1.
* Otherwise, f(n) = 1 + f(n - 1) + f(n - 2).
So, f is at least O(fib(n)). In fact, f(n) is 2 * fib(n) - 1. We show
this by induction:
* Base cases (n < 2, that is, n = 0 or n = 1):
o f(n) = 1 = 2 * 1 - 1 = 2 * fib(n) - 1.
* Induction step (n >= 2):
o f(n + 1) = f(n) + f(n - 1) + 1
o f(n + 1) = 2 * fib(n) - 1 + 2 * fib(n - 1) - 1 + 1
o f(n + 1) = 2 * fib(n + 1) - 1
Modifying the find_fib by including a counter variable,I computed:
fib(25) =121393
Number of times called : 242785