for (int i = 0; i < n^2; i++) {
for (int j = 1; j < i; j = 2j) {
for (int k = 0; k < j; k++) {
System.out.println("x");
}
}
}
My thoughts are that the outer loop is n^2, middle loop is log(n) and inner loop is n so that means the total time complexity is O(n^3 * log(n)) but I'm not sure if this is right.
The complexity of the following nested loop:
...is O(4):
The value of
nis only used inn^2, so let's definem=n^2The first two iterations of the outer loop do nothing (the j-loop condition is immediately false), so we can start at 2 instead of 0.
The print statement is an O(1) operation, so the inner loop is O().
We can then write the code like this:
Now let's rewrite the j-loop defining
paslog(j)(all logarithms here have base 2):the inner loop's complexity represents a geometric sum so it has a closed formula, and we can rewrite:
The loop's body will have repeatedly the same value for
qfor some different values ofiuntiliovertakes the next power of 2. We could introduce a variableqequal toceil(log(i)), which makes its own iterations:As the value of
idoesn't matter anymore for the inner loop, we can use its number of iterations as a coefficient for the big Oh expression:To be fair, the condition
i < mwould limit the number of iterations of the previous inner loop when the outer loop is in its last iteration, but asymptotically this is not significant.We can simplify:
Which is again a geometric sequence, summing up to:
O(4log())
= O([2log()]2)
= O(2)
= O(4)