Big O for 3 nested loops

假如想象 提交于 2019-11-28 07:15:05

问题


Another Big O notation question...What is the Big O for the folling code:

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

My Thoughts: So breaking it down, I think the outside loop is O(log2(n)), then each of the inner loops is O(n) which would result in O(n^2 * log2(n)) Question #1 is that correct?

Question #2: when combining nested loops is it always just as simple as mulitply the Big O of each loop?


回答1:


When loop counters do not depend on one another, it's always possible to work from the inside outward.

The innermost loop always takes time O(n), because it loops n times regardless of the values of j and i.

When the second loop runs, it runs for O(n) iterations, on each iteration doing O(n) work to run the innermost loop. This takes time O(n2).

Finally, when the outer loop runs, it does O(n2) work per iteration. It also runs for O(log n) iterations, since it runs equal to the number of times you have to divide n by two before you reach 1. Consequently, the total work is O(n2 log n).

In general, you cannot just multiply loops together, since their bounds might depend on one another. In this case, though, since there is no dependency, the runtimes can just be multiplied. Hopefully the above reasoning sheds some light on why this is - it's because if you work from the inside out thinking about how much work each loop does and how many times it does it, the runtimes end up getting multiplied together.

Hope this helps!




回答2:


  1. Yes, this is correct: the outer loop is logN, the other two are N each, for the total of O(N^2*LogN)
  2. In the simple cases, yes. In more complex cases, when loop indexes start at numbers indicated by other indexes, the calculations are more complex.



回答3:


To answer this slightly (note: slightly) more formally, say T(n) is the time (or number of operations) required to complete the algorithm. Then, for the outer loop, T(n) = log n*T2(n), where T2(n) is the number of operations inside the loop (ignoring any constants). Similarly, T2(n) = n*T3(n) = n*n.

Then, use the following theorem:

If f1(n) = O(g1(n)) and f2(n) = O(g2(n)), then f1(n)×f2(n) = O(g1(n)×g2(n))
(source and proof)

This leaves us with T(n) = O(n2logn).

"Combining nested loops" is just an application of this theorem. The trouble can be in figuring out exactly how many operations each loop uses, which in this case is simple.




回答4:


You can proceed formally using Sigma Notation, to faithfully imitate your loops:



来源:https://stackoverflow.com/questions/14510701/big-o-for-3-nested-loops

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