int n=3;
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = n - 1; j >= i; j = j - 2) {
sum = i + j;
System.out.println(sum);
}
}
i've been trying to find the complexity of this code (O(?) etc)
any ideas?
int n=3;
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = n - 1; j >= i; j = j - 2) {
sum = i + j;
System.out.println(sum);
}
}
i've been trying to find the complexity of this code (O(?) etc)
any ideas?
I'll explain just to clear my own understanding. The first loop run n
times. Now, let's discuss the inner loop.
First iteration, it will run from n-1
to 0
inclusive, with increments of 2, resulting in n/2
iterations. Second Iteration, it will run from n-1
to 1
inclusive, with increments of 2, resulting in (n-1)/2
iterations. And so on, the last iteration will be from n-1
to n-1
inclusive, and it will be 1
iteration.
Counting all iterations, it will be [n/2 + (n-1)/2 + .... 1] ≈ n2
Well, constant, for the fixed n... :-) But if you want a complexity in n, it's O(n^2) - it would be o(n^2) if the inner cycle went from n to 0, but as it is, we only reduce the time in half by ending at i (imagine a square; the area where j >= i is a triangle), and by another half by stepping j by 2, which together is just a constant multiplicative factor 1/4 (IOW not changing the asymptotic complexity).