问题
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