What is the asymptotic runtime of fthe ollowing piece of code in terms of number of updates to S in worst case.
Void foo( int n)
{
int S = 0;
for ( i=1 ; i<= n ; i++)
{
for( j = 1 ; j<= i*i ; j++)
{
if(j % i == 0)
{
for( k=1 ; k<=j ; k++)
s++;
}
}
}
}
My way :
Outer for loop will execute 'n' time.
Middle for loop will execute 'n^3' times. Because j is reaching to i*i.
So if n =10 ,i will move from 1 to 10. j will execute 1*1 + 2*2 + 3*3 + ..... + 10*10. i.e. 1^2 + 2^2 + ... + n^2 = maximum term is n^3.Inner for loop will execute maximum 'n' times. Suppose n = 10 , and i reaches to 10 i.e. i = 10 , so j can reach 1 to 10 * 10. In this maximum 10 times i.e. n times 'if loop' condition will be fulfilled.
so total n * n^3 * n = Theta ( n^5 )
But answer is given as Theta ( n^4 ) and explained in totally mathematical terms ( which I didnt get )
Did I make any mistake ?