问题
public void foo(int n, int m) {
int i = m;
while (i > 100) {
i = i / 3;
}
for (int k = i ; k >= 0; k--) {
for (int j = 1; j < n; j *= 2) {
System.out.print(k + "\t" + j);
}
System.out.println();
}
}
I figured the complexity would be O(logn).
That is as a product of the inner loop, the outer loop -- will never be executed more than 100 times, so it can be omitted.
What I'm not sure about is the while clause, should it be incorporated into the Big-O complexity? For very large i values it could make an impact, or arithmetic operations, doesn't matter on what scale, count as basic operations and can be omitted?
回答1:
The while
loop is O(log m)
because you keep dividing m
by 3
until it is below or equal to 100
.
Since 100 is a constant in your case, it can be ignored, yes.
The inner loop is O(log n)
as you said, because you multiply j
by 2
until it exceeds n
.
Therefore the total complexity is O(log n + log m)
.
or arithmetic operations, doesn't matter on what scale, count as basic operations and can be omitted?
Arithmetic operations can usually be omitted, yes. However, it also depends on the language. This looks like Java and it looks like you're using primitive types. In this case it's ok to consider arithmetic operations O(1)
, yes. But if you use big integers for example, that's not really ok anymore, as addition and multiplication are no longer O(1)
.
回答2:
The complexity is O(log m + log n).
The while loop executes log3(m) times - a constant (log3(100)). The outer for loop executes a constant number of times (around 100), and the inner loop executes log2(n) times.
回答3:
The while loop divides the value of m by a factor of 3, therefore the number of such operations will be log(base 3) m
For the for loops you could think of the number of operations as 2 summations -
summation (k = 0 to i) [ summation (j = 0 to lg n) (1)] summation (k = 0 to i) [lg n + 1] (lg n + 1) ( i + 1) will be total number of operations, of which the log term dominates.
That's why the complexity is O(log (base3) m + lg n) Here the lg refers to log to base 2
来源:https://stackoverflow.com/questions/2984229/tricky-big-o-complexity