Big O of Nested Loop (int j = 0; j < i * i; ++j)

风流意气都作罢 提交于 2020-02-01 09:20:40

问题


Question 1

for (i = 0; i < n; i++) {
  for (j = 0; j < i * i ; j++){

  }
}
Answer: O(n^3)

At first glance, O(n^3) made sense to me, but I remember a previous problem I did:

Question 2

for (int i = n; i > 0; i /= 2) {
   for (int j = 0; j < i; j++) {
     //statement
   }
}
Answer: O(n)

For Question 2, the outer loop is O(log n) and the inner loop is O(2n / log n) resulting in O(n). The inner loop is O(2n / log n) because - see explanation here: Big O of Nested Loop (int j = 0; j < i; j++)


Why we don't do Question 1 like Question 2 since in Question 1, j also depends on i which means we should really be taking the average of how many iterations will occur in the inner loop (as we do in Question 2).

My answer would be: O(n) for the outer loop and O(n^2 / n) for the inner loop which results in O(n^2) for Question 1.


回答1:


Your answer is wrong. The code is Θ(n³).

To see that note that the inner loop takes steps which is at most but for half of the outer loop iterations is at least (n/2)² = n²/4.

Therefore the number of total inner iterations is at most n * n² = n³ but at least n/2 * n²/4 = n³/8.


Your consideration is wrong in that the inner loop takes on average proportional to many iterations, not n² / n.




回答2:


What your inner for loop is doing, in combination with the outer for loop, is calculating the sum of i^2. If you write it out you are adding the following terms:

1 + 4 + 9 + 16 + ...

The result of that is (2n^3+3n^2+n)/6. If you want to calculate the average of the number of iterations of the inner for loop, you divide it by n as this is the number of iterations of the outer for loop. So you get (2n^2+3n+1)/6, in terms of Big O notation this will be O(n^2). And having that gives you... nothing. You have not gain any new information as you already knew the complexity of the inner for loop is O(n^2). Having O(n^2) running n times gives you O(n^3) of total complexity, that you already knew...

So, you can calculate the average number of iterations of the inner for loop, but you will not gain any new information. There were no cuts in the number of iteration steps as there were in your previous question (the i /= 2 stuff).




回答3:


void fun(int n, int k) 
{ 
    for (int i=1; i<=n; i++) 
    { 
      int p = pow(i, k);  
      for (int j=1; j<=p; j++) 
      { 
          // Some O(1) work 
      } 
    } 
} 

Time complexity of above function can be written as 1k + 2k + 3k + … n1k.

In your case k = 2

Sum = 12 + 22 + 32 + ... n12.
    = n(n+1)(2n+1)/6
    = n3/3 + n2/2 + n/6


来源:https://stackoverflow.com/questions/59872524/big-o-of-nested-loop-int-j-0-j-i-i-j

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