简体   繁体   English

确定算法的时间复杂度

[英]Determine the time complexity of an algorithm

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):代码执行integer除法(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.我的答案是 O(n),因为在最坏的情况下,当我们有 a > 0,b = 1 时,我们将在while()循环中迭代a次。

The answer in the book was O(a/b) which makes sense.书中的答案是 O(a/b),这是有道理的。 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). O(a/1) => O(a) <=> O(n) (在这种情况下括号中的字母并不重要)。

So, the answer O(n) is correct as well.所以,答案 O(n) 也是正确的。 Isn't it?不是吗?

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".你的回答没有意义,原因很简单,问题陈述中没有 n,说 a 是 n 是“作弊”。

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.此外,虽然它在技术上是正确的,但当您知道该算法恰好进行 a/b 加法时,使用不紧束缚的 O(a) 有点令人难过。


By the way, it is an arbitrary decision to say that b=1 is "the" worst case.顺便说一句,说 b=1 是“最坏”情况是一个武断的决定。 Better say worst case for fixed a (and variable b), or for fixed b (and variable a).最好说固定 a(和变量 b)或固定 b(和变量 a)的最坏情况。

Alas there is no generalisation of big-O to multi-variable one, see Formal definition of big-O when multiple variables are involved?唉,没有将 big-O 推广到多变量,请参阅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.但是正如您知道确切的复杂性,T(a,b)=a/b,不需要最坏情况……当我们不知道如何计算确切的复杂性时,我们使用最坏情况分析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM