Here is my function. It is a simple one, I’m just not confident on what the answer is.
int calcul( int n) {
if(n=1)
return 1;
else
return calcul(n/2) + 1;
}
Now, to get the complexity, I do:
T(n) = T(n/2) + O(1)
T(n/2) = T(n/4) + O(1)
…
T(1) = O(1)
Now, adding the equations, I’m getting
T(n) = O(1) + O(1)…
so what is the final answer ?
You’re executing the function once for each time you can divide
nby2, which islog ntimes.So you get
O(log n).Edit:
The logarithm (of base 2) of a number
nis the power2has to be raised to getn.That is,
2^(log n) = n, where^indicated exponentiation.Now, a simple way to calculate an approximation of
log nis dividenby2whilen > 1.If you’ve divided
ktimes, you getn < 2^k.Since
k - 1divisions still yieldedn > 1, you also haven >= 2^(k-1).Taking logarithms on each member of
2^(k - 1) <= n < 2^k, you getk - 1 <= log n < k.