what is the order of growth of this code segment?Explain little bit

时间:2017-04-24 17:14:56

标签: java algorithm big-o

int sum = 0;
for (int i = 0; i*i < N; i++){
   for (int j = 0; j*j < 4*N; j++){
        for (int k = 0; k < N*N; k++){
                sum++;
        }
    }
}

i know the order of growth of this code segment is N^3.But i need proper explain for this.

2 个答案:

答案 0 :(得分:2)

I know the order of growth of this code segment is N^3

Yes, you're right.

The total number of execution is sqrt(N) * sqrt(4 * N) * (N^2) which is -

sqrt(N) * sqrt(4 * N) * (N^2)
=> 2 * sqrt(N) * sqrt(N) * (N^2)
=> 2 * N * (N^2)
=> 2 * (N^3)
=> O(N^3)

答案 1 :(得分:1)

You can analyse the loops step by step, because the counters are independent of each other:

  1. Outer loop: executed sqrt(n) times.

  2. Middle loop: executed sqrt(4 * n) = 2 * sqrt(n) times.

  3. Inner loop: executed n^2 times.

  4. Multiply the results: sqrt(n) * 2 * sqrt(n) * n^2 = 2 * n^3.

Thus follows O(n^3).