Time complexity analysis. while loop with inner for loop [duplicate]

ε祈祈猫儿з 提交于 2019-12-11 04:47:08

问题


I'm trying to find the number of times this code runs. On the right I have my attempt at the code. I'm am not sure about the loops. Here is the code:

                         times
sum = 0                    1
i = 1                      1 
while i ≤ n                log n + 1
 sum = sum + i             n log n
 i = 2i                    log n
return sum                  1

=> n log n + 2 log n + 4

and thereby: O(n log n)

is this correct ?


回答1:


No, your analysis is incorrect. Note that each iteration of the inner loop does O(1) work, so the total time complexity can be found by multiplying the number of loop iterations by O(1).

In this case, the loop runs for O(log n) iterations, since i can only double O(log n) times before it exceeds n. Therefore, the total time complexity is O(log n).

Hope this helps!



来源:https://stackoverflow.com/questions/21501752/time-complexity-analysis-while-loop-with-inner-for-loop

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