3

I would like to know the time complexity of the following algorithm. At first glance the time complexity looks to be O(n^5) and that is what is mentioned in majority of the sites i have seen on the internet. But a careful analysis seems to give a different answer, here is the code:

public void fun(int n)
{
   int i,j,k,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++;
            }
       }
   }
}
sasidhar
  • 7,523
  • 15
  • 49
  • 75

1 Answers1

2

Note that j%i c== 0 will yield true O(i) times (for each distinct i) - thus the inner loop will repeat itself O(i) times in each "outer" iteration.

Thus the complexity is O(n*n^2 + n*n^3) = O(n^4)

Explanation:
O(n*n^2) is for the "middle loop" which repeats itself regardless of the evaluation of the if condition. It is O(n^3) since you get: 1 + 4 + 9 + 16 + ... + n^2 which is a sum of squares and is O(n^3).
O(n*n^3) is a bit trickier:

For each i, each inner loop repeats i times, so for each i you get: i + 2i + 3i + ... + (i-1)i total repeats of the inner loop. It is easy to see that it is in fact i(1 + 2 + ... + i-1) which is O(i^3).

Now, we can see that since it happens for each i - the total complexity will be (not being formal, just intuitive): O(1^3) + O(2^3) + ... + O(n^3) which is O(n^4) from sum of cubed series

Conclusion:
Though cold analysis might have shown O(n^5) - since the inner loop does not repeat itself for each iteration of the middle loop - the total complexity is O(n^4)

Community
  • 1
  • 1
amit
  • 175,853
  • 27
  • 231
  • 333