简体   繁体   English

带有 if 语句的嵌套 for 循环的时间复杂度

[英]Time Complexity of Nested for Loops with if Statements

How does the if-statement of this code affect the time complexity of this code?此代码的 if 语句如何影响此代码的时间复杂度?

Based off of this question: Runtime analysis , the for loop in the if statement would run n*n times.基于这个问题:运行时分析,if 语句中的 for 循环将运行 n*n 次。 But in this code, j outpaces i so that once the second loop is run j = i^2 .但是在这段代码中, j超过了i ,因此一旦运行第二个循环j = i^2 What does this make the time complexity of the third for loop then?那么这使第三个 for 循环的时间复杂度如何呢? I understand that the first for loop runs n times, the second runs n^2 times, and the third runs n^2 times for a certain amount of times when triggered.我知道第一个 for 循环运行 n 次,第二个运行n^2次,第三个在触发时运行n^2次。 So the complexity would be given by n*n^2(xn^2) for which n is the number of times the if statement is true.因此,复杂性将由n*n^2(xn^2)给出,其中n是 if 语句为真的次数。 The complexity is not simply O(n^6) because the if-statement is not true n times right?复杂性不仅仅是O(n^6) ,因为 if 语句不是真的 n 次,对吧?

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

The if condition will be true when j is a multiple of i ;ji的倍数时, if条件为真; this happens i times as j goes from 0 to i * i , so the third for loop runs only i times.j从 0 变为i * i时,这会发生i次,因此第三个for循环仅运行i次。 The overall complexity is O(n^4).总体复杂度为 O(n^4)。

for (int i = 1; i < n; i++)
{
  for (int j = 0; j < i*i; j++)       // Runs O(n) times
    {
      if (j % i == 0)                 // Runs O(n) × O(n^2) = O(n^3) times
        {
          for (int k = 0; k < j; k++) // Runs O(n) × O(n) = O(n^2) times
            {
              sum++;                  // Runs O(n^2) × O(n^2) = O(n^4) times
            }
        }
    }
}

The complexity is not simply O(n^6) because the if-statement is not true n times right?复杂性不仅仅是 O(n^6),因为 if 语句不是真的 n 次,对吧?

No, it is not.不它不是。

At worst, it is going to be O(n^5) .在最坏的情况下,它将是O(n^5) It is less than that since j % i is equal to 0 only i times.它小于这个值,因为j % ii次等于0

The first loop is run n times.第一个循环运行n次。
The second loop is run O(n^2) times.第二个循环运行O(n^2)次。
The third loop is run at most O(n) times.第三个循环最多运行O(n)次。

The worst combined complexity of the loop is going to be O(n) x O(n^2) x O(n) , which is O(n^4) .循环的最差组合复杂度将是O(n) x O(n^2) x O(n) ,即O(n^4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM