0

assume that I have an if clause

if (!f(x))
{
   g(x);
}

the complexity of f(x) = O(x^3) and complexity of g(x) = O(x^2). In this case what is the overall complexity ? O(x^5) ? or O(x^3) ?

I wanted to increase my question sizes.

while(z(x))
{
  for(p(x))
  {
     if (!f(x))
     {
       g(x);
     }
  }
}

where, z(x) = O(x^5), p(x) = O(x),f(x) = O(x^3), g(x) = O(x^2)

zaratushtra
  • 53
  • 2
  • 7

3 Answers3

5

The total complexity is O(x3) because you have an x3 operation followed (possibly) by an x2 operation. The former dominates the latter: O(x3) + O(x2) = O(x3).

TypeIA
  • 16,916
  • 1
  • 38
  • 52
  • thanx for the answer. what about if clause has if(f(x) && h(x)){g(x)}, where f(x)=O(x^3) and h(x)=O(x^2) and g(x)=O(x^2). – zaratushtra Jan 20 '14 at 22:00
  • 1
    @zaratushtra Same result for the same reasons; 3 sequential operations, and the x^3 term dominates. – TypeIA Jan 20 '14 at 23:01
0

You need to remember that 'O' complexity exhibit upper bound for that algorithm. Think wrt worst case scenario (upper bound).

In your first case, if your 'if' condition succeed complexity would be O(x3) + O(x2), which will be equivalent to O(x3). since if condition will execute once so you try to add up orders and highest order will define the upper bound.

Now in your second example. Loops will multiply their order with code covered by them. So complexity would be O(x5)O(x)(O(x3) + O(X2)). The upper bound of which come out to be O(X8).

Manish Shukla
  • 562
  • 6
  • 18
0

For first example it is O(x^3) because O(x^3) dominates over O(x^2) in big-O notation. Second example O(infinity) because you dont know when the while loop will end, it may go on for ever so big-O is O(infinity) . lower bound for it is O(x^5) because it might get false in first iteration of while

Vikram Bhat
  • 6,106
  • 3
  • 20
  • 19