0

What is the time complexity of the following piece of code in worst case?

s=0; 
for(i=1;i<=n;++i){

   for(j=1;j<=i*i;j++){

       for(k=1;k<=j and j%i==0;k++)     /*  k<=j  and j%i==0 */
           s++;

   }
}

Each loop depend on the outer loop variable.How to proceed in such case? Innermost loop will run only sometimes.How to evaluate this case?

For every increment of i middle loop runs for i^2 times and for every iteration of middle loop,I think innermost loop iterates for i times. Middle loop run for j=1 to i^2 and j%i!=0 is in i cases and for other i cases j%i=0. As inner loop run for j%i==0 it would be iterated i times.
Now as innermost loop run for i times,middle loop run for i^2 times and outer loop run for i times , I think complexity would be n^4

For every i of outer loop, innermost loop run for $i(i^2+i)/2$ times.Evaluating a summation over $i(i^2+i)/2$ for i=1 to n will get me a polynomial of degree four. So its complexity should be $O(n^4)$.Am I correct?

Ashish Pani
  • 101
  • 1
  • 7
    Welcome! Since we get a lot of questions about this kind of thing, we've written a reference question, which covers most of the common techniques. Please check it out and, if it doesn't help you to find a solution, let us know where you got stuck. – David Richerby Oct 27 '15 at 13:49
  • There isn't really a "worst" case here, since given $n$ anything else is determined. – Yuval Filmus Oct 27 '15 at 15:11

0 Answers0