Say I have a for
loop like this
for(int i=1;i<n;i=i*2)
{
for(int j=1;j<i;j=j*2)
{
cout<<"hello";
}
}
What is the time complexity of this loop?
I have approached this problem like this. The outer loop runs log(n)
times and the inner loop runs log(i)
times, so in total the complexity becomes $O(log(log(n)))$
Whereas, my friend has approached it like this. The outer loop is running,
$i=2^0$+$2^1$+$2^2$+$2^3$.... $2^{log(n)}$
times and since the inner loop is running log(i)
times, so the total time complexity we have is
$TC=0+1+2+3...log(n)= O( (log(n))^2 )$
Which of these two is correct $O(log(log(n)))$ or $O( (log(n))^2 )$ ?