Time complexity analysis. while loop with inner fo

2019-08-08 23:03发布

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条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-08 23:35

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!

查看更多
登录 后发表回答