0

Here's the code I've implemented in a nutshell. The for loop should have a complexity of O(n). I just can't figure out the time complexity of the inner while loop.

int x,n; // Inputted by the user.
for (int i=0; i<n; i++)
{
 int done=0;
 if (Condition)
 {
 while (done < x)
 {
 done++; // Based on a lot of operations
 }
 }
}

I can post the whole code if you want. Thanks in advance :)

asked Nov 10, 2014 at 10:25
7
  • 1
    The overall inner loop complexity is O(x). But since you do not reset done to 0 the x times that the "inner operations" are run get done all over the outer loop. In the end, these operations are only executed x times. Commented Nov 10, 2014 at 10:37
  • 1
    Then, it gets run each time Condition is triggered, not just the first time. The inner loop complexity stays O(x) (taking the number of times your operations are run as a metrics) Commented Nov 10, 2014 at 10:53
  • 1
    @Rerito Would the overall complexity be O(xn) in this case? Commented Nov 10, 2014 at 10:53
  • 2
    The inner loop complexity is O(x). Once combined with the outer loop, you get a worst-case complexity of O(xn). Commented Nov 10, 2014 at 10:55
  • 2
    Time complexity is at most O(nx). Since we dont know what 'Condition' is we cant tell more accurately. Commented Nov 10, 2014 at 10:56

1 Answer 1

2

Here, the complexity is measured by studying the number of times the program will run the operations of the inner loop.

Each time Condition is triggered, the inner loop runs x times. Thus the inner loop complexity is O(x).

This loop can run at most n times. This provides you an overall worst-case complexity of O(x.n).

Having additional knowledge about Condition can get you a more precise analysis. You may be able to compute average complexity for example.

As an example : let Condition be !(i & (i-1)). This is true if and only if i is either 0 or a power of 2. In this case, your loop would get run exactly E(ln2(n)) + 2 times (E(.) being the integer part function). In the end, the overall complexity knowing this becomes O(x.ln(n))

answered Nov 10, 2014 at 11:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.