0
for ( int i = 1; i < n*n*n; i *= n ) {
    for ( int j = 0; j < n; j += 2 ) { 
        for ( int k = 1; k < n; k *= 3 ) { 
            cout<<k*n;
        }
    }
}

I am facing an issue with this exercise, where I need to find the big O notation of the following code, but I got O(n^5) where the first loop is n^3, 2nd loop n, and the 3rd loop is n and I am not sure if I am correct or not. Can someone help me please?

Jason
  • 36,170
  • 5
  • 26
  • 60
Q_i99i
  • 13
  • 3

3 Answers3

1

First loop is i=1 and every time multiplies by n until its n^3 so its 3 times, which is O(1).
Second loop is j=1 and every time added 2 until its n so its n/2 times, which is O(n).
Third loop is k=1 and multiplies by 3 until its n, which is O(log(n))
Overall: O(n*log(n))

Ofirfr
  • 76
  • 1
  • 5
1

Your analysis is not correct.

The outer loop multiplies i by n each ietration,starting from 1 till n^3.
Therefore there will be 3 iterations which is O(1).

The middle loop increments j by 2 each iteration, starting from 0 till n.
Therefore there will be n/2 iterations which is O(n).

The inner loop multiplies k by 3, from 1 till n.
Therefore there will be log3(n) iterations, which is O(log(n)).
If this step is not clear, see here: Big O confusion: log2(N) vs log3(N).

The overall time complexity of the code is a multiplication of all the 3 expressions above (since these are nested loops).

Therefore is it: O(1) * O(n) * O(log(n)), i.e.: O(n*log(n)).

wohlstad
  • 12,661
  • 10
  • 26
  • 39
0

You are not correct. In first loop for ( int i = 1; i < n*n*n; i *= n ) pay attention to "statement 3"(i *= n), and in third loop for ( int k = 1; k < n; k *= 3 ) also pay attention to "statement 3"(k *= 3). Your calculation for second loop is great.

DimitrijeCiric
  • 446
  • 1
  • 10
  • is it log n and log n? Just found out what is *= += -= xD – Q_i99i May 14 '22 at 13:12
  • The second loop will iterate n/2 times, in big O notation, it will be O(n). The first loop will iterate 3 times which is O(1), and the third loop will iterate log3(n) times which is O(log3(n)). So total time complexity is O(1)*O(n)*O(log3(n)) which is O(n*log3(n)). – DimitrijeCiric May 14 '22 at 13:23
  • 2
    @Q_i99i If you don't even know what the code does, then why do you try to analyze its complexity? That can't work. Learn the basics of the language first. – user17732522 May 14 '22 at 13:32
  • Its a complexity exercise – Q_i99i May 14 '22 at 13:34