I am beginer and i am confuse how the time complexity of this code is loglogn.
while(i<=n)
{
i = i*i;
}
I am beginer and i am confuse how the time complexity of this code is loglogn.
while(i<=n)
{
i = i*i;
}
For n = k16:
iteration 1: i = k
iteration 2: i = k^2
iteration 3: i = k^4
iteration 4: i = k^16
So basically you can show that you are iterating log(m) times for km, where m = log(k).
Let us define the start value for i as j, then at the start of the first iteration, the value for i is j. At the end of the iteration, the value for i is j2.
Now the next iteration, at the end, the value for i is j4. If at the start of the k-th iteration, the value is jl, then at the end of the iteration, the value of j2×l.
So that means at the k-th iteration, the value will be j2k. We will keep iterating until we reach a value for i such that i > j, so that means that:
j2k > n
we can here apply the logj to both parts:
2k > logjn
and the log2 to both:
k > log2(logjn)
for the first k for which this happens, the loop will end. So that means that this will happen "between" the log2(logjn) and log2(logjn)+1 iteration, but the +1 does not matter here.
The time complexity is thus: O(log2(logjn)) with j the initial value for i, and n the bound in the while loop.