1
for i = 0 ... log(n) - 1
    for j = 2^i + 1 ... 2^(i + 1)
         [code with Big-Theta(1) running time]

Given this piece of code the outer loop runs log(n) times. But I'm confused as to how to try to calculate the running time of the second loop so as to multiply them. Thank you for reading.

1 Answers1

1

Each internal loop does $2^i$ iterations of $\Theta(1)$ so it takes $\Theta(2^i)$. Therefore the time complexity of the code is the $\Theta(\Sigma_{i=0}^{log(n)} 2^i)=\Theta(n)$.

You could intuitively think of summation here as writing in binary base a number where all its digits are 1, and has the same number of digits as n, it is linear to the size of n.

David Taub
  • 632
  • 4
  • 11