for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
j=j*2;
}
}
I am having trouble generalizing it.
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
j=j*2;
}
}
I am having trouble generalizing it.
If we count the number of multiplication the program does, the complexity will be n * log2(n)
You do n
times the inner loop (i
scales with n
), and the inner loop repeats as long as j <= n
. j
increase exponentially
1, 3, 7, 15, 31, 63, 127, ... = (2^n) - 1
Which is 2^n
scaling, so double the value of n
makes the inner loop iterate once more.
log2(n * 2) = log2(n) + 1