The code fragment I am to analyse is below:
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < i * i; j++)
for (int k = 0; k < j; k++)
sum++;
I know that the first loop is O(n) but that’s about as far as I’ve gotten. I think that the second loop may be O(n^2) but the more I think about it the less sense it makes. Any guidance would be much appreciated.
The first loop executes
ntimes. Each time, the valueigrows. For each suchi, the second loop executesi*itimes. That means the second loop executes1*1 + 2*2 + 3*3 + ... + n*ntimes.This is a summation of squares, and the formula for this is well-known. Hence we have the second loop executing
(n(1 + n)(1 + 2 n))/6times.Thus, we know that in total there will be
(n(1 + n)(1 + 2 n))/6values of j, and that for each of these the third loop will execute1 + 2 + ... + j = j(j+1)/2times. Actually calculating how many times the third loop executes in total would be very difficult. Luckily, all you really need is a least upper bound for the order of the function.You know that for each of the
(n(1 + n)(1 + 2 n))/6values ofj, the third loop will execute less thann(n+1)/2times. Therefore you can say that the operationsum++will execute less than[(n(1 + n)(1 + 2 n))/6] * [n(n+1)/2]times. After some quick mental math, that amounts to a polynomial of maximal degree 5, therefore your program isO(n^5).