I am confused to the time complexity of this piece of code and the logic used to find it.
void doit(int N) {
for (int k = 1; k < N; k *= 2) { <----I am guessing this runs O(logN)
for (int j = 1; j < k; j += 1) { <------I am not sure how this one works.
}
}
}
I have already tried solving it out by hand writing it out. But, I still don't understand it.
Thank you for your time.
EDIT:
Adding another question to it. Same concept, different format.
void doit(int N) {
int j, k; //I ended up getting this answer to be O(n^(n/2)) But then I was stuck after that...is that even the right answer?
for (k = 1; k < N / 2; k += 1) {
for (j = k; j < 2 * k; j += 1) [
x[j] = x[j-k] + x[j];//This doesn't really matter
}
}
}
The total complexity is actually
O(N)
Claim: For each
k
you havek
inner loop iterations. (convince yourself why it is correct)Denote the number of total inner loops iterations by
T(N)
, and let the number of outer loops beh
.This means we have:
(1) From sum or geometric series
(2) Note that the equality
2^(h+1) = 2^(logN + 1)
is becauseh = logN
, we have (as you said)logN
outer loop iterations.