I am trying to determine the worst case runtime of this program:

while n > 1
  for i = 1,..,n
    m = log(n)
  n = n/2

Obviously the outer loop runs log(n) times, because n is halfed after each step.

But the inner for loop is dependent on the decreasing n and I am not quite sure how to deal with that.

A simple bound for it would be n, so the whole thing runs in at most log(n)*n, but I am sure the inner loop is faster than that.

If I look at each step of the outer loop, I see that the inner loop runs n,n/2,n/4,..,2 times. So I would say all together the inner loop runs at most 2n times which is in O(n).

Can I just deduct from that fact that the overall runtime is O(log(n)+n) = O(n)?

I am unsure because I am not multiplying anything, which I feel like I should when dealing with multiple loops.


When loops are nested, the running time is the amount of time the innermost loop is executed multiplied by the time it takes to execute the body of the loop. In your case, the innermost loop executes $n+n/2+n/4+\dots+1\lt2n$ and we'll assume that computing the $\log$ takes constant time. So the running time is linear in $n$.

| cite | improve this answer | |
  • $\begingroup$ So I can just completely disregard the outer loop if I know the running time of the innermost loop? There is another operation in the outer loop here after all. $\endgroup$ – magnattic Mar 26 '13 at 19:47
  • $\begingroup$ The running time is just how many times the line m = log(n) is executed. That's what I meant. $\endgroup$ – saadtaame Mar 26 '13 at 19:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.