Finding Big O Notation of For loop which is inside an If condition

空扰寡人 提交于 2020-03-25 18:32:29

问题


sum = 0;
for( i = 1; i < n; ++i )
  for( j = 1; j < i * i; ++j )
    if( j % i == 0 )
      for( k = 0; k < j; ++k )
        ++sum;

How do I find Big O notation for this code? I'm new to this big o notation thing. So I'll appreciate if someone can explain me it simply with details.. Thank you!


回答1:


Big O is an asymptotic upper bound of a function. So in your case the the for loops take the most time, if the if condition evaluates always to true, so you can just assume this an get a correct upper bound, which is maybe not tight. But there are a lot of cases where you cannot do better than this.

In some cases you can try to remove the if while maintaining the number of operations roughly. E.g. in your case you could replace j = 1 by j = i and ++j by j += i. This is not to change the algorithm, but only for the complexity analysis to change the way you look at it. You still have to remember that the middle for loop takes i*i steps. Now you have this:

sum = 0;
for( i = 1; i < n; ++i )
  O(i * i) Operations
  for( j = i; j < i * i; j += i )
    for( k = 0; k < j; ++k )
      ++sum;

You also can assume that the if condition is always false. This way you get a lower bound. In some cases the upper and lower bound match, meaning that the part you hat trouble to analyze is actually irrelevant for the overall complexity.



来源:https://stackoverflow.com/questions/59015083/finding-big-o-notation-of-for-loop-which-is-inside-an-if-condition

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