How does this if statement affect the time complexity?

主宰稳场 提交于 2020-03-20 01:37:35

问题


I know that the first two loops are O(n^3), but I am not sure how the if statement affects the time complexity.

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

回答1:


The if statement has a huge impact in the overall complexity of this code.

Without if it would be O(n^5) but with if it is O(n^4).

Since j has a range from 1 to i*i and the if will work only when j % i = 0.

That means for each i, j will work i^2 and there are i cases when j % i = 0.

So, the overall complexity will be O(n^4).

To get an idea how it goes, I just compile the code:

   static int count;

   static void rr(int n)
   {
      for (int i = 1; i < n; i++)
      {
         for (int j = 1; j < i * i; j++)
         {
            if (j % i == 0)
            {
               for (int k = 0; k < j; k++)
               {
                  count++;
               }
            }
         }
      }
   }

   public static void main(String[] args)
   {
      for (int n = 50; n < 110; n += 10)
      {
         count = 0;
         rr(n);
         System.out.println("For n = " + n + ", Count: " + count);
      }
   }

Here is the output.

With if

For n = 50, Count: 730100
For n = 60, Count: 1531345
For n = 70, Count: 2860165
For n = 80, Count: 4909060
For n = 90, Count: 7900530
For n = 100, Count: 12087075

Without if

For n = 50, Count: 29688120
For n = 60, Count: 74520894
For n = 70, Count: 162068718
For n = 80, Count: 317441592
For n = 90, Count: 574089516
For n = 100, Count: 975002490

So, with if the complexity is O(n^4).



来源:https://stackoverflow.com/questions/59868331/how-does-this-if-statement-affect-the-time-complexity

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