简体   繁体   中英

How do i calculate the time complexity of this function?

Hi everyone i tried to calculate the time complexity of this function but i can't really understand how to calculate the complexity of that "for loop"

01    int* f(int a[], int n) {
02    int i = 1;
03    int *s;
04    s = calloc(n, sizeof(int));
05    while (i < n) {
06        for (j=0; j < i; j++)
07           s[i] = s[i] + a[j];
08        i = i*2;
09    }
10    return s;
11    }

The exercise asks for the time complexity in relation to the dimension "n" of the array

I don't think lines 02,03,04 are a big problem because they should have a O(1) complexity

For the while loop if i leave aside the "for loop" for a moment,since "i" is multiplied by two each time the time complexity should be 2^k<n --> k= log_2(n)

But what about the for loop? it should be executed "i" times,but how can i express this in relation to "n"?

PS : how do i write math symbols?i can't find anything in the editor

The outer loop is executed log(n) times, with i taking the values 1, 2, 4, 8, ... <n, where <n is the largest power of 2 less than n.

For each value of i , the inner loop is executed i times.

So you have 1 + 2 + 4 + 8 ... + <n. This sum is less than 2*n. So the answer is O(n).

Some other people thought this was O(n*log(n)), but the mistake they made was multiplying the outer trip count times the maximum trip count of the inner loop. To get the correct answer, you need to take into account that the inner loop trip count doubles each time, so the later trip counts dwarf the earlier ones.

For the first iteration inner loop will run once,for second twice,for third iteration inner loop will run 4 times and so on.So

 2^0 + 2^1 + 2^2 + 2^3 +.....+2^i where 2^i < n

We can find i by taking log both sides of 2^i < n which gives i=log2(n)

2^0 + 2^1 +...+2^(log2(n)) ie 2^0 + 2^1 + ...+ n

But

i < log2(n) and not i=log2(n).

So the previous value of n would be n/2

So finally we have

2^0 + 2^1...+n/2

The dominant term is n/2 so its O(n/2) which is O(n)

It's actually tricky question. Technically your observation is correct. The inner loop will be executed up to n times, so it looks like the complexity is O(n*log2(n)) .

But that's not really correct. The issue is that for the first execution of while the inner for loop is executed once, next time twice, next time four times etc., up to n/2 (rounded to next power of two, so up to n ). So altogether it sums up to 1+2+...n/2 which is O(n ). Ie linear complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM