i try to find the complexity of this algorithm:
m=0;
i=1;
while (i<=n)
{
i=i*2;
for (j=1;j<=(long int)(log10(i)/log10(2));j++)
for (k=1;k<=j;k++)
m++;
}
I think it is O(log(n)*log(log(n))*log(log(n))):
- The ‘i’ loop runs until i=log(n)
- the ‘j’ loop runs until log(i) means log(log(n))
- the ‘k’ loop runs until k=j –> k=log(i) –> k=log(log(n))
therefore O(log(n)*log(log(n))*log(log(n))).
The time complexity is Theta(log(n)^3).
Let T = floor(log_2(n)). Your code can be rewritten as:
Which is obviously Theta(T^3).
Edit: Here’s an intermediate step for rewriting your code. Let a = log_2(i). a is always an integer because i is a power of 2. Then your code is clearly equivalent to:
The other changes I did were naming floor(log_2(n)) as T, a as i, and using a for loop instead of a while.
Hope it’s clear now.