这些代码片段的运行时间有哪些Big-Oh值?

时间:2014-11-18 08:16:16

标签: big-o

我想知道是否有人可以帮助我解决这些代码片段的Big-Oh运行时间并解释你如何获得每个代码...谢谢!

a。)

int x = 0;
    for (int i = 0; i < n; i += 4){
         for (int j = 0; j < i; j++){
              x += i*j;
         }
    }

b。)

int counter = 0;
    for (int i = 1; i < n; i = i*3){
        for (int j = n*n; j >= 0; j--){
             counter++;
        }
    }

c。)

int x = 0;
    int i = 1;
    while (i < n){
        int j = 0;
        while (j < 2*n){
             x++;
             j = j+n;
        }
        i = i*2;
   }

1 个答案:

答案 0 :(得分:1)

我会告诉你如何解决第一个问题然后你可以为所有人做同样的事情。

在第一个问题中,你有两个循环。在外部循环中,您从0开始,并在每次迭代中以n的增量上升到4。表示您的外循环将运行n/4次。现在,

For 1st iteration of outer loop your inner loop will run 0 or 0*4 times.
For 2nd iteration of outer loop your inner loop will run 4 or 1*4 times.
For 3rd iteration of outer loop your inner loop will run 8 or 2*4 times.

In general,
For pth iteration of outer loop your inner loop will run (p-1)*4 times.

number of times your innermost loop ran = 0*4 + 1*4 + 2*4 .............+ ((n/4)-1)*4.
                                        = 4 * (1+2+3..........+ (n/4)-1)
                                        = 4 * ((n/4)-1) * (n/4) * 1/2
                                        = (n^2)/8 + n/2
                                        = O(n^2)