Algorithm Time Complexity: i/=2 in loops

断了今生、忘了曾经 提交于 2021-02-04 14:06:44

问题


int fun(int n) {
    int count = 0;
    for (int i = n; i > 0; i /= 2)
        for (int j = 0; j < i; j++)
            count += 1;
    return count;
}

I'm a very new to the time complexities calculations. For this algorithm, I get the answer to be O(nlogn), but the answer is apparently O(n).

My logic was the outer loop has an exponential decline and will occur log_base2_(N) times. The inner loop will run a total of N times as it becomes a geometric sum (first iteration it is N/2 times, then N/4, then N/8 ...). If I put these together and multiply them as a result of the nested loop, that's where I'm coming up with O(NlogN). Am I missing something obvious?


回答1:


The outer loop would run a total of log(n) times. Now if you observe the inner loop it first time it runs n times, next n/2 times and so on, so it makes the series

n(1 + 1/2 + 1/4 + 1/8 + 1/16 + ...)

the sum of this would be (2*n), That means it is O(n)

Hence the time complexity is O(n) since outer loop runs O(logn) times and inner loop runs O(n) times.

It is not O(nlogn) since the inner loop does not take n steps each time, in fact the sum of all steps taken would be O(n)



来源:https://stackoverflow.com/questions/46195687/algorithm-time-complexity-i-2-in-loops

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!