为什么 counter = counter /2;有 O(log(n))?

发布于 2024-10-25 23:30:43 字数 233 浏览 0 评论 0原文

我知道以下代码的复杂度为 O(log(n)):

while (n>1)
{
    counter++;
    n/=2;
}

我知道这里,n 在每次迭代中被分成两半,这意味着如果 n是 1000 则需要十轮才能跳出循环。这是如何导致 O(log(n)) 的?

抱歉问了这个简单的问题,在问之前我真的尽力了。

I know the following code has a complexity of O(log(n)):

while (n>1)
{
    counter++;
    n/=2;
}

I understand that here, n is being divided in half on each iteration, meaning that if n was 1000 then it will take ten rounds to get out of the loop. How did this lead to O(log(n))?

Sorry for the simple question, I really tried my best to get it before I asked.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

虫児飞 2024-11-01 23:30:43

每次循环时,您都会除以 2(粗略地;这将忽略舍入,因为它是渐近参数)。因此,如果开始时 n = N,则经过 k 次迭代后,n=N/(2^k)。要达到 n = 1,您必须满足 2^k = N。即 k = log(N)。

Each time through the loop, you divide by 2 (roughly; this will ignore rounding since it is an asymptotic argument). So if n = N at the start, after k iterations, n=N/(2^k). To arrive at n = 1, you have to satisfy 2^k = N. That is, k = log(N).

微凉徒眸意 2024-11-01 23:30:43

递推关系将是

 T(n) = T(n/2) + O(1)

尝试使用 Master 定理 来解决它,将给出 T(n ) 为 O(log n)(类似于二分查找中得到的结果)。

The recurrence relation would be

 T(n) = T(n/2) + O(1)

Trying to solve it using Master's theorem will give the running time of T(n) as O(log n) (similar to what you get in Binary Search).

贪恋 2024-11-01 23:30:43

假设 n 是 2^x(例如 2^5=32、2^10=1024 等),因此计数器在循环内递增 x 次。根据定义,x 是以 2 为底的 log n。

Imagine that n is 2^x (e.g. 2^5=32, 2^10=1024 etc), so that the counter is incremented x times within the loop. By definition, x is a base 2 log n.

南汐寒笙箫 2024-11-01 23:30:43

根据定义,对数不是线性的。换句话说,它们根据输入的不同而改变不同的量。在您的示例中,第一步将 n 减少了 500,而第五步仅将其减少了 32。越接近 1,n 减少的速度就越慢。这种“减速”正是日志所表现出的行为。

By definition, logarithms aren't linear. In other words, they change by different amounts depending on the input. In your example, the first step takes n down by 500, while the fifth step reduces it by only 32. The closer you get to one, the slower n decreases. This "deceleration" is exactly the kind of behavior you get with a log.

君勿笑 2024-11-01 23:30:43

一个简单的解释:如果你加倍 n 会发生什么?运行时间是否加倍(即 O(n))?不,运行时间仅增加一步。这是典型的 O(log n)。

[OTOH,如果你对 n 进行平方(假设它从 4 增加到 16),那么你会发现步数加倍。再次表示 O(log n)。]

A simple hand-wavey explanation: What happens if you double n? Does the runtime double (that would be O(n))? No, the runtime increases by only one step. This is typical of O(log n).

[OTOH, if you squared n (say it increased from 4 to 16), then you find the number of steps double. Again, indicative of O(log n).]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文