A Loop That Doubles
Here is a contrived example of a loop where the loop counter is multiplied by a constant each iteration, rather than added to.
public int myStrangeSum(int num) {
int sum = 0;
for (int i = 1; i < num; i *= 2) {
sum += i;
}
return sum;
}
Let be the value of num. What is the Big-Oh of this method?
The body of the loop is constant work, so the only question is how many times the loop runs. i doubles each iteration instead of going up by one. It takes the values , and the loop stops once i reaches or passes , because the condition is i < num.
So how many doublings does it take to get from up to ? That is the same question we asked about binary search. There we kept halving until we got down to , and the answer was . Here we keep doubling until we get up to . The values are the same, . We just go through them in the other direction, so there are the same number of them. If it helps to see the halving version directly, this loop runs the same number of times:
for (int i = num / 2; i > 0; i /= 2) {
sum += i;
}
Take to be a power of two if you want the counts to match exactly. When is not a power of two, the two counts can be off by one, and one step does not change how the work grows.
Either way, the loop runs about times, and the body is constant work, so this method is .
When a loop counter is multiplied or divided by a constant each time, rather than added to, the loop runs a logarithmic number of times.
Does the base of the logarithm matter?
The base of the logarithm does not matter for Big-Oh. A logarithm with a different base is just a constant multiple of the one you have, so it is in the same class. In practice, the base does matter, because it changes the constant factor, but Big-Oh ignores that.