Binary counter increment analysis [00SZ]

How long does this algorithm take?

  • The best case is \Theta (1): if the last bit of n is 0 then all we have to do is flip it. The while loop never executes at all.
  • The worst case is when n is of the form 2^k - 1, that is, all 1 bits, and to increment it we have to flip all the 1’s to 0s and then set the next 0 bit to 1. Since n requires \Theta (\lg n) bits to represent it, this means that incrementing n takes \Theta (\lg n) in the worst case.

Therefore, a sequence of n increment operations takes \Omega (n) time in the best case, and O(n \lg n) in the worst case. However, we don't typically do a bunch of random increment operations; more realistically, we start a counter at 0 and repeatedly increment up to n. We can observe that many such operations will be best cases, and that the worst case happens only infrequently. Can we say something more precise about how long it takes to perform a n increment operations (and thus how long a single increment operation takes on average)?