算法的渐近复杂度(Big - O)
我有以下示例:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在内循环中,
j
以i
步从2i
到n
,因此内循环运行(n-2i)/i+1
次,即n/i-1
(整数除法)。然后外层循环从
2
到n
运行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 from2i
ton
in stepsi
, so the inner loop runs(n-2i)/i+1
times, which isn/i-1
(integer division).Then the outer loop runs with
i
from2
ton
, for a total ofn/2-1+n/3-1+n/4-1+...n/(n/2)-1
inner iterations (for largeri
, there are no iterations).This quantity is difficult to estimate, but is bounded above by
n (H(n/2)-1)-n/2
whereH
denotes an Harmonic Number.We know that
Hn~O(log n)
, hence, asymptotically, the running time isO(n log n)
.