This would be part # 2 of my question about analysis of for loop running time
http://faculty.simpson.edu/lydia.sinapova/www/cmsc250/LN250_Weiss/L03-BigOhSolutions.htm#PR4 contains solutions, and I have question about two particular “for” loops
Could someone explain to me how to figure out running time for both of them. Thanks !
1.
sum = 0;
for( i = 0; i < n; i++)
for( j = 0; j < i*i; j++)
for( k = 0; k < j; k++)
sum++;
2.
sum = 0;
for( i = 0; i < n; i++)
for( j = 0; j < i*i; j++)
if (j % i ==0)
for( k = 0; k < j; k++)
sum++;
The first snippet is
O(n^5).Here’s the closed-form solution of the first snippet: (computed via Mathematica)
This is a 5th order polynomial, therefore it is:
O(n^5)The second snippet appears to be
O(n^4).Here’s the closed-form solution of the second snippet: (computed via Mathematica)
This is a 4th order polynomial, therefore it is:
O(n^4)Further explanation of the effect of the if-statement:
The middle loop iterates from 0 to
i*i. The if-statement checks ifjis divisible byi. But that is only possible whenjis a multiple ofi.How many times is
ja multiple ofiif0 <= j < i*i? Exactlyitimes. Therefore only1/iof the iterations of the middle loop will fall through to the inner-most loop.