Calculating algorithmic complexity

130 Views Asked by At

Given the following bit of code, how would I calculate the complexity?

for (a = 0; a < i; a++) {
    //some code
    //some code
    for (b = 0; b < j; b++) {
        //code
        for (c = 0; c < k; c++) {
            //code
        }
    }
}

Assuming the commented lines have complexity of 1, would the complexity be calculated as follows?

a loop happens $i$ times

b loop happens $i^2j$ times

c loop happens $i^3j^2k$ times

Complexity = $2i + i^2j + i^3j^2k$?

1

There are 1 best solutions below

3
On BEST ANSWER

Start with the inner c loop. Suppose you add a counter statement ctr++; to it. Because there loop count is k, one complete c loop adds k to the counter and therefore one pass through the b loop adds k to the counter: there are j passes of the b loop and thus a total increment of j*k. Repeat the argument for the i passes of the a loop and you get an overall count of i*j*k for your whole code snippet.