帮助找到该算法的复杂性
我试图找到这个算法的复杂性:
m=0;
i=1;
while (i<=n)
{
i=i*2;
for (j=1;j<=(long int)(log10(i)/log10(2));j++)
for (k=1;k<=j;k++)
m++;
}
我认为它是 O(log(n)*log(log(n))*log(log(n))):
- “i”循环运行直到 i=log(n )
- 'j' 循环运行直到 log(i) 意味着 log(log(n)) '
- k' 循环运行直到 k=j --> k=log(i) --> k=log(log(n))
因此 O(log(n)*log(log(n))*log(log(n)))。
i try to find the complexity of this algorithm:
m=0;
i=1;
while (i<=n)
{
i=i*2;
for (j=1;j<=(long int)(log10(i)/log10(2));j++)
for (k=1;k<=j;k++)
m++;
}
I think it is O(log(n)*log(log(n))*log(log(n))):
- The 'i' loop runs until i=log(n)
- the 'j' loop runs until log(i) means log(log(n))
- the 'k' loop runs until k=j --> k=log(i) --> k=log(log(n))
therefore O(log(n)*log(log(n))*log(log(n))).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
时间复杂度为Theta(log(n)^3)。
令 T = 下限 (log_2(n))。您的代码可以重写为:
这显然是 Theta(T^3)。
编辑:这是重写代码的中间步骤。令 a = log_2(i)。 a 始终是整数,因为 i 是 2 的幂。那么您的代码显然相当于:
我所做的其他更改是将 Floor(log_2(n)) 命名为 T,将 a 命名为 i,并使用 for 循环而不是 a尽管。
希望现在已经清楚了。
The time complexity is Theta(log(n)^3).
Let T = floor(log_2(n)). Your code can be rewritten as:
Which is obviously Theta(T^3).
Edit: Here's an intermediate step for rewriting your code. Let a = log_2(i). a is always an integer because i is a power of 2. Then your code is clearly equivalent to:
The other changes I did were naming floor(log_2(n)) as T, a as i, and using a for loop instead of a while.
Hope it's clear now.
这是作业吗?
一些提示:
我不确定代码是否做了它应该做的事情。 log10 返回一个浮点值,转换为 (long int) 可能会减少 0.9999999999。我不认为这是有意的。该行可能看起来像这样:
在这种情况下,您可以将其重写为:
因此,您对“j”和“k”循环的复杂性假设是错误的。
(外层循环运行 log n 次,但 i 一直增加到 n,而不是 log n)
Is this homework?
Some hints:
I'm not sure if the code is doing what it should be. log10 returns a float value and the cast to (long int) will probably cut of .9999999999. I don't think that this is intended. The line should maybe look like that:
In that case you can rewrite this as:
Therefore your complexity assumption for the 'j'- and 'k'-loop is wrong.
(the outer loop runs log n times, but i is increasing until n, not log n)