How to find a complexity of the following algorithm:
int f(int n)
{
if(n<=1) { return 1; }
return f(n-1) + f(n-1);
}
Is it correct recursion equation T(n) = 2*T(N-1) + c
? How to solve it?
How to find a complexity of the following algorithm:
int f(int n)
{
if(n<=1) { return 1; }
return f(n-1) + f(n-1);
}
Is it correct recursion equation T(n) = 2*T(N-1) + c
? How to solve it?
I think your recursion equation is correct.
But this specific case is easy enough, to "just think" about it a bit without going further into "how to solve recursions in general".
Let's have a look at f(3)
f(3)
f(2) + f(2)
f(1) + f(1) + f(1) + f(1)
So, how many calls do we have? 1 + 2 + 4
Hmm.. how about f(4)?
f(4)
f(3) + f(3)
f(2) + f(2) + f(2) + f(2)
f(1) + f(1) + f(1) + f(1) + f(1) + f(1) + f(1) + f(1)
So, how many calls do we have? 1 + 2 + 4 + 8
So we can make an educated guess for n=5: 1+2+4+8+16. And if you think about it, it also makes sense because: numCalls(f(5)) = 2*numCalls(f(4)) + 1 (the + 1 stems from the call to f(5) itself).
We can generalize this to
T(n) = sum(2^i) for i in (0, n-1)
Now, if we use the fact that
sum(2^i) for i in (0, n-1) == 2^n - 1
it becomes very obvious that
T(n) = 2^n - 1
which is in O(2^n)
Left as an exercise:
Prove by induction that
T(n) = 2*T(n-1) + 1 <=> T(n) = 2^n - 1
Or a bit more general:
T(n) = 2*T(n-1) + c <=> T(n) = c*(2^n - 1)
Just as a side-note as suggested in the comments: you can drastically improve perfomance by using memoization