The core idea
For a loop of the shape
i = i0;
while (i <= n) {
/* O(1) body */
i = f(i);
}
the running time is when the body is . The iteration count is decided entirely by the update rule . The recipe is always the same three steps:
- Track the counter. Write , the value of after executions of the body, as a closed form in .
- Find the stopping point. The body runs while ; solve for .
- Invert to get . Whatever function grew is inverted to count the steps: repeated addition inverts to division, repeated multiplication inverts to a logarithm, repeated squaring inverts to a double logarithm.
The three update families
| Update rule | Closed form (from ) | Stops when | Iterations |
|---|---|---|---|
| (additive) | |||
| (multiplicative, ) | |||
| (squaring) |
The pattern is a clean ladder: each time you make the update one operation "stronger" (add multiply square), you peel off one logarithm from the iteration count. Going the other way (e.g. shrinking down to a constant) also yields by the same inversion.
Why squaring gives
Start at and square each step. The exponent doubles every iteration:
because . The loop stops when
Taking once undoes the outer power; taking it a second time undoes the doubling of the exponent. So the number of iterations is — and since the body is , the total time is .
How to apply it
- Read the update line, not the test. The comparison
i <= nonly tells you the bound; the growth speed comes fromi = f(i). - The starting value only changes lower-order constants. As long as for a multiplicative/squaring loop, the asymptotic order is unchanged. (Beware with
i = i*i— it never grows: — an infinite loop, a classic trap.) - For nested loops, multiply the per-loop counts. A
*2outer loop wrapping a+1inner loop is , etc.
Worked mini-example
How many times does the body run?
i = 2;
while (i <= n) { i = i * i; }
The update is squaring, so . It stops when , i.e. . Hence the body runs times and the loop is . Contrast the same loop bound with a multiplicative update i = i * 2, which would give , stopping at — an exponentially larger — showing how much the single update operator matters.
Exam trick: Don't be fooled by
i <= ninto guessing . Identify the update operator:+,\times, squaring . Each step up in operator strength removes one .