从循环和条件语句计算时间复杂度

时间:2014-10-12 13:31:03

标签: algorithm time-complexity

我使用每个循环O(n)的时间复杂度来计算。 从代码的每一行开始,时间复杂度为:

= 1 + n *((n * (1 + n * 1)) + (n * 1)))
= 1 + n * (n * (n + 1) + n)
= 1 + n * (n^2 + n + n)
= 1 + n^3 + n^2 + n^2
= 1 + n^3 + 2 * n^2` 

所以它是O(n^3)

我的计算是否正确?

int result = 0 ;             //1
for (int i = 0 ; i <N ; i++){  //n 
    for (int j = 0 ; j <N ; j++){ //n

        for (int k = 0 ; k <N ; k++){ //n 

            int x = 0 ; //1
            while (x < n ){ //n 
            result ++ ; //1 
             x+=3 ; //1
        }

        }

        for(int k = 0 ; k<2*M ; K++){ //n
            if(K%7 == 4) 
                 result ++ ;
        }   

    }

}

2 个答案:

答案 0 :(得分:0)

如果时间复杂度可以表示为a(n ^ 3)+ b(n ^ 2)+ c(n)+ d,其中a,b,c和d是常数,时间复杂度为O(n ^ 3)。

我猜,你是对的。

答案 1 :(得分:0)

快速浏览后,我猜测复杂度为O(N ^ 4)。我认为这是一个猜测,因为提供的代码有一些拼写错误,这可能会改变它的含义。我在下面提供了我的解释:

int result = 0 ;
for (int i = 0 ; i <N ; i++) { // N
  for (int j = 0 ; j <N ; j++) { //N * N

    for (int k = 0 ; k <N ; k++) { // N*N*N
      int x = 0 ; //1
      while (x < N ){ //This was x < n, but n was undefined, so assumed N. N^4
        result ++;  
        x+=3;
      }
    }

    for(int k = 0 ; k<2*N ; k++) { //N*N*(2*N), this was k<2*M, but M was undefined
        if(k%7 == 4) result++;
    }   
  }
}

是的,正如你在上面看到的那样,for循环是三层深,每次从0迭代到N;这很容易看出给我们O(N ^ 3)。然而,我们在最里面也有一个while循环,它也可以用N来表征 - 特别是N/3 - 它将我们带到O(N ^ 4)。