I find it easier to do it the other way around in cases like this. What is the opposite of what you're doing (even approximately)? Something like:
for (a = 1; a <= n; a = a * 8)
{
...
}
Now, we've changed the while
to a for
, which has a fixed number of steps, and decrementation to incrementation, which can be easier to work with.
we have:
1, 8, 8^2, ..., 8^k <= n
8^k <= n | apply logarithm
log (8^k) <= log n
k log 8 <= log n
=> k = O(log n)
So your while loop executes O(log n)
times. If you have something that is O(n^3)
inside, then your entire sequence will be O(n^3 log n)
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…