大O在有限的,固定大小的设置可能值大小

2023-09-11 05:47:43 作者:怪咖遇奇葩走路萌哒哒

This 引起了一些混乱,有关在各种答案中提出的算法是否为O(1)或O(N)。

This question triggered some confusion and many comments about whether the algorithms proposed in the various answers are O(1) or O(n).

让我们用一个简单的例子来说明这两种观点:

Let's use a simple example to illustrate the two points of view:

我们希望找到一个长 X ,使得 A * X + B = 0 ,其中 A B 是已知的,非空多头。

we want to find a long x such that a * x + b = 0, where a and b are known, non-null longs. 在一个明显的O(1)算法中的 X = - B / A 在慢得多的算法中会包括在测试中每一个可能的长期价值,这将是平均慢2 ^ 63次。

时的第二个算法O(1)或O(N)?

Is the second algorithm O(1) or O(n)?

psented的链接问题的争论$ P $是:

The arguments presented in the linked questions are:

这是O(n),因为在最坏的情况下,你需要遍历所有可能的long值 这是O(1),因为它的复杂性是形式 CX O(1) ,其中 C = 2 ^ 64 是一个常数。 it is O(n) because in the worst case you need to loop over all possible long values it is O(1) because its complexity is of the form c x O(1), where c = 2^64 is a constant.

虽然我明白的说法说,这是O(1),感觉违反直觉。

Although I understand the argument to say that it is O(1), it feels counter-intuitive.

PS:我加的Java 作为原问题是在Java中,但这个问题是语言无关。

ps: I added java as the original question is in Java, but this question is language-agnostic.

推荐答案

的复杂性是唯一相关,如果有一个变量N所以,问题是没有意义的原样。如果问题是:

The complexity is only relevant if there is a variable N. So, the question makes no sense as is. If the question was:

一个慢得多算法中会包括在测试中每一个可能的价值在区域N的值,这将是大约N倍速度较慢的平均水平。

A much slower algo would consist in testing every possible value in a range of N values, which would be about N times slower on average.

时的第二个算法O(1)或O(N)?

Is the second algorithm O(1) or O(N)?

那么答案将是:这个算法是O(N)

Then the answer would be: this algorithm is O(N).