331 views
1 votes
1 votes

I am posting que as well as its solution.... i am cleared about 1st two loops i and j but how to calculate complexity for innermost loop??

please explain... how this is an answer?

1 Answer

Best answer
1 votes
1 votes

for(i=1;i<=n;i++)

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

        if((j%i)==0)

       {    for(k=1;k<=j;k++);

            // some text

     }

}

Execution ;

Step 1- Outermost for loop is executes O(n) time.

Check for inner for loop 

if i=1 and j=1 [((j%i)==0) is true]  then k=1 time executed.

if i=2 and j=1;j<=4

[(j%i)==0] is true only for half of values of j.  i.e)j=2,j=4.then k is executed 2 times.

if i=3 and j=1:j<=9 

[(j%i)==0] is true for j=3,6,9 [i.e i times] but j is check condition for j=1 to 9 in which only 3 times k is executed.

..

...

if i=n and j is executed until n*n and only $\frac{n^{2}}{n}$=n is succesful.This 'n' time innermost k loop is executed.

Hence 

Time for first for loop=O(n)

and Second for loop=O($n^{2}$) 

Third for loop =O(n)  // only n values are true in total of $n^{2}$.

Total time complexity=O(n*$n^{2}$*n)=O($n^{4}$)

selected by

Related questions

1 votes
1 votes
1 answer
1
Rackson asked Jan 20, 2019
600 views
0 votes
0 votes
2 answers
2
Gate Fever asked Sep 27, 2018
1,986 views
0 votes
0 votes
1 answer
3
0 votes
0 votes
3 answers
4