8

I was just reading another question and this code intrigued me:

for(i = 0; i < n; i++)
{
    for(j = 0; j < i*i; j++)
    {
        for(k = 0; k < i*j; k++)
        {
            pseudo_inner_count++;
            for(l = 0; l < 10; l++);
        }
    }
}

I don't understand how this can be O(N^6). Can someone break it down for me?

Community
  • 1
  • 1
karlphillip
  • 92,053
  • 36
  • 243
  • 426

3 Answers3

15

Actually it is:

  • The i loop iterates O(N) times, so the value of i is O(N), so we can say O(I)=O(N).
  • The j loop iterates O(I^2) = O(N^2) times (when considered on its own, without the outer loop).
  • The k loop iterates O(I*J) = O(N*N^2) = O(N^3) times.
  • The l loop just iterates 10 times so that is O(1).

The loops are nested so we have to multiply these together (do you understand why?). The total is O(N)*O(N^2)*O(N^3) = O(N^6).

David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • Ok, so the final result is achieved through a multiplication of the evaluations of each loop, and not through a sum (as @Pascal suggested). Can someone else confirm this? – karlphillip Jul 21 '11 at 05:00
  • 2
    Pascal did not really do the sum. He multiplied n * n^2 * n^2 * n and got n^6. It might look like a sum because the exponents add together but that's just how exponents work in math. – David Grayson Jul 21 '11 at 05:03
  • @karl: Well law of exponents say we add the exponents since the terms we're multiplying have the same base. I don't see how you came to the conclusion that he's taking the sum of something. – Jeff Mercado Jul 21 '11 at 05:05
  • 1
    @karlphillip: Think about it, it only makes sense to multiply. For example, if an inner loop performs some operation 5 times, and then an outer loop performs the inner loop 10 times, then the operation is performed 5*10=50 times. Big O notation is similar, except that you are multiplying functions. [Note: this is a useful but non-rigorous way of thinking about it!] – antinome Jul 21 '11 at 05:13
1

It's

n for the first loop n² for the second loop n³ for the third loop

The inner loop is O(1)

The total is O(n⁶).

The reason the third loop is n³ is because when you think about it j reaches n² and i reaches n, so i*j reaches n³.

Paul
  • 139,544
  • 27
  • 275
  • 264
-1

I would say :

  • n for the first loop
  • n² for the second loop => total of n³
  • n² for the third loop => total of n⁵
  • yet another n-loop => total of n⁶
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663