算法的渐近复杂度(Big - O)

发布于 2025-01-14 11:50:32 字数 202 浏览 1 评论 0原文

我有以下示例:

i=2;
while i<=n {
   O(1)
   j=2*i
   while j<=n {
       O(1)
       j=j+i
   }
   i=i+1

我是计算渐近复杂度的初学者。我认为它是 O((n-1)*(n/4)) 但我不确定这个答案是否正确或者我遗漏了一些东西。

I've got the following example:

i=2;
while i<=n {
   O(1)
   j=2*i
   while j<=n {
       O(1)
       j=j+i
   }
   i=i+1

I'm a beginner at calculating asymptotic complexity. I think it is O((n-1)*(n/4)) but I'm not sure if this answer is correct or I'm missing something.

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

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

发布评论

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

评论(1

再可℃爱ぅ一点好了 2025-01-21 11:50:32

在内循环中,ji 步从 2in,因此内循环运行 (n-2i)/i+1 次,即 n/i-1(整数除法)。

然后外层循环从 2n 运行 i,总共 n/2-1+n/3- 1+n/4-1+...n/(n/2)-1 次内部迭代(对于较大的 i,没有迭代)。

该数量很难估计,但其边界为 n (H(n/2)-1)-n/2,其中 H 表示谐波数。

我们知道Hn~O(log n),因此,渐进地,运行时间为O(n log n)

In the inner loop, j goes from 2i to n in steps i, so the inner loop runs (n-2i)/i+1 times, which is n/i-1 (integer division).

Then the outer loop runs with i from 2 to n, for a total of n/2-1+n/3-1+n/4-1+...n/(n/2)-1 inner iterations (for larger i, there are no iterations).

This quantity is difficult to estimate, but is bounded above by n (H(n/2)-1)-n/2 where H denotes an Harmonic Number.

We know that Hn~O(log n), hence, asymptotically, the running time is O(n log n).

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