could you plese tell me the asymptotic complexity of this code?
f(n):
if (n<=2) then return 1;
else {
if (n>950) then { i=n/2; return f(i);}
else return f(n-2);
}
I have thought of two solutions.
a)
O(1) when n<=2
T(n/2) + 1 when n > 950
T(n-2) + 1 when 950>=n>2
and solving the recurrences:
O(1) when n<=2
Θ(log n) when n > 950
O(n^2) when 950>=n>2
b) However I'm not so sure about the complexity of the last two statements, because if n is bigger than 950 the alghorithm will call f(i) until i is smaller than 950 and then proceed calling f(n-2). So, the other solution is this one:
O(1) when n<=2
T(n/2) + T(n-2) + 1 otherwise
and solving the recurrences:
O(1) when n<=2
O(n^2) otherwise
I actually think the second one is right, but I'm not sure of it. Thanks for your help.
okay, so start by thinking about what happens if n is really big. Eventually n will be big enough it will dominate everything else. And sure enough, until you get down to n=950 you're going to get O(lg n) where "lg" denotes log base 2. (Why do I know this off hand?because the size of n decreases by a power of two every iteration.)
Once n is down to 950, then it's going to decrease by 2 every time, so from 950 to 2 is O(n) -- because you hit basically half the values and that 1/2 disappears into the constant.
But observe that there exists a value of n for which lg n > 950/2. Ergo the lg n term will dominate for some value of n. O(lg n).