Direct calculation [00T5]
Sometimes, we can actually compute a formula for the total T(n) of a sequence of n operations—or at least show that the total T(n) is bounded by some simple formula. Then we can calculate the amortized time for a single operation as T(n)/n.
As an example, let's try coming up with a formula for the total number of bit flips needed to increment a binary counter from 0 to n. We have T(n) = 1 + 2 + 1 + 3 + 1 + 2 + 1 + 4 + 1 + 2 + 1 + 3 + 1 + 2 + 1 + 5 + \dots Incidentally, this pattern is sometimes called the ruler function since it looks like a traditional ruler showing inches, half inches, quarter inches... with each subsequent marking being shorter:
It's not obvious how to come up with a formula for T(n), but a change of perspective is often helpful, such as rearranging the terms being added or slicing them a different way. In this case, if we draw the terms being added with dots, it looks like this:
Instead of adding up each column, we can think about adding by rows. The bottom row contains n dots, because the last bit flips with every single increment. The second-to-last row contains \lfloor n/2 \rfloor dots, because the second-to-last bit flips every other increment. The third-to-last row contains \lfloor n/4 \rfloor dots, and so on. Hence T(n) = n + \lfloor n/2 \rfloor + \lfloor n/4 \rfloor + \lfloor n/8 \rfloor + \dots This formula is exact, since at some point \lfloor n/2^k \rfloor becomes zero, for k > \lg n.We still don't know how to simplify this exactly, but we don't need to: remember that we are just trying to show that T(n) < 2n. So we can compute as follows: