0

This is a follow up question to How to count the number of operations including an 'if... else...' statement?

I do not understand the answer from the poster and will appreciate if someone can clarify.

I have the code with the number of operations:

if (a < b)              - 1 operation
    print("Hello")      - 1 operation
    print("World")      - 1 operation
else
    print("Goodbye")    - 1 operation
    print("World")      - 1 operation
    print("Sad")        - 1 operation

Case 1 : If a = 5 and b = 6, is the total number of operations 3?

Case 2 : If a = 6, b = 5, is the total number of operations 4?

Or will the total number of operations be 7?

Is it right to say that we only count the number of operations given that the condition fulfill for either 'if' or 'else'?

user3118602
  • 553
  • 5
  • 19

2 Answers2

0

You are correct for both case 1 and case 2.

The total number of operations would depend on the input received.

So, in the worst case (case 2: where a > b), the total number of operations would be 4.

The best case (case 1: where a < b), is when the if condition is true, as that takes 3 operations (1 less operation than case 2).

There wouldn’t be any time where that code would have a total number of operations higher than 4 because only one or the other condition is being fulfilled. There is no possible instance where both conditions could be met.

0

Take the condition in the if statement and calculate the complexity of it if it's a comparison operation then it's O(1) or omega 1 thus theta 1 as well. you don't count having the numbers to compare as operations as well. Now getting into the calculation of the complexity part unless it would involve or depend on some function that could be defined in some variable we take it to be O(1) meaning constant time thus not focusing too much on the exact operations taking place. Now whether a or b would be greater depends on the values of a and b. At max in this case it would have 4 operations. but as that's a constant number we could simply conclude that it takes constant amount of time.