1

This question is for revision from a past test paper just wondering if i am doing it right.

im new to this, so im having a bit of difficulty with more complicated questions. this is one of them...

If anyone could elaborate on this, i'll be very grateful... So i have to find out the complexity of this piece of code...

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

so, i tried doing it...and i got O(n^2logn).. its not correct...the answer should be O(n^2).. can somebody help me on this ?

4
  • I would have thought it would be O(n^3). When i=0, then the complexity is O(n^2), but then when i=n, the complexity is O(n^3). Commented Nov 6, 2013 at 18:27
  • I guess k should be initted to 0. Commented Nov 6, 2013 at 18:28
  • i is not equal to 0 or n in the sense used above; it is the loop variable, after all. Commented Nov 6, 2013 at 18:30
  • yeah..made a mistake...correcting it :) thanks Commented Nov 6, 2013 at 18:31

2 Answers 2

1

The number of iterations of the second loop is $$ 1 + 3 + 9 + ... + m $$ where $m$ is roughly $n$. This sums to $\Theta(n)$. Then the innermost loop is another factor of Theta(n). So $\Theta(n^2)$.

Sign up to request clarification or add additional context in comments.

Comments

1

A formal manner to determine the time complexity of your algorithm:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.