Search code examples
algorithmtime-complexitybig-ocomputer-sciencecomplexity-theory

How to calcualte the Big-O complexity of the following algorithm?


I have been trying to calculate the Big-O of the following algorithm and it is coming out to be O(n^5) for me. I don't know what the correct answer is but most of my colleagues are getting O(n^3).

for(i=1;i<=n;i++)
{
    for(j=1 ; j <= i*i ; j++)
    {
        for(k=1 ; k<= n/2 ; k++) 
        {
        x = y + z;
        }
     }
}

What I did was start from the innermost loop. So I calculated that the innermost loop will run n/2 times, then I went to the second nested for loop which will run i^2 times and from the outermost loop will run i times as i varies from 1 to n. This would mean that the second nested for loop will run a total of Sigma(i^2) from i=1 to i=n so a total of n*(n+1)*(2n+1)/6 times. So the total amount that the code would run came out to be in the order of n^5 so I concluded that the order must be O(n^5). Is there something wrong with this approach and the answer that I calculated?

I have just started with DSA and this was my first assignment so apologies for any basic mistakes that I might have made.


Solution

  • The inner loop always has the same number of iterations (n/2), since it is independent of i and j. On its own it has a complexity of O(n).

    The two other loops result in a sum of sequence of squares (1 + 4 + 9 + ...) of executions of the inner part.

    This sum of squares corresponds to the square pyramidal number, and has an order of O(n3).

    The inner loop has an order of O(n), so we get O(n4).