2

I'm reading one cool book, and there was a task to determine the time complexity of the code in the worst case. The code performs integer division (a > 0, b > 0):

int div(int a, int b) {
    int count = 0;
    int sum = b;
    while (sum <= a) {
        sum += b;
        count++;
    }
        
    return count;
}

My answer was O(n), since, in the worst case, when we have a > 0, b = 1, we will iterate through a times in the while() loop.

The answer in the book was O(a/b) which makes sense. But, if we're considering the worst case, then

O(a/1) => O(a) <=> O(n) (letter in parentheses doesn't really matter in this case).

So, the answer O(n) is correct as well. Isn't it?

2
  • 4
    i think you wrote sub instead of sum inside your while condition Commented Dec 8, 2022 at 8:55
  • @Olli yes, spelling mistake Commented Dec 8, 2022 at 9:19

2 Answers 2

2

Alas there is no generalisation of big-O to multi-variable one, see Formal definition of big-O when multiple variables are involved?.

But as you know the exact complexity, T(a,b)=a/b, there is no need for worst-case... We use worst-case analysis when we don't know how to compute the exact complexity.

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

1 Comment

Also when we want to remain on the safe side.
2

Your answer does not make sense for the simple reason that there is no n in the problem statement, and saying that a is n is "cheating".

Also, though it is technically correct, it is a little sad to use an untight bound O(a) when you know that the algorithm makes exactly a/b additions.


By the way, it is an arbitrary decision to say that b=1 is "the" worst case. Better say worst case for fixed a (and variable b), or for fixed b (and variable a).

2 Comments

From the task description, I know that a and b are always > 0.
@SergeyChernikov: you are right. I am rephrasing.

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.