时间复杂度

arczee 2006-01-02 10:59:40
请教各位,下面算法的时间复杂度是多少,我认为是O(log2n) 其中2为底
不知道对不对

i = s = 0;
while ( s < n)
{
i ++; /* i = i +1*/
s += i; /* s = s + i*/
}
...全文
139 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
murphykwu 2006-01-04
  • 打赏
  • 举报
回复
因为循环了n次
O(logn)
ox_thedarkness 2006-01-04
  • 打赏
  • 举报
回复
恩,纠正的纠正....偶最开始说的是对的, 然后说我说的是错的那贴是错的.... 正确答案仍然是 O(n开方),亦即 jp1984(compiler) 的答案。
orz。。。回贴后看到YufengShi(浪子) 的,头脑短路了。。。

作为对比,下面这个才是 log2n
s = 0;
i = 1;
while ( s < n)
{
i*=2; // i = 2^t
s += i; // s = 2 + 4 + 8 + ... + 2^t = 2^(t+1) - 2 ~ O( 2^t )
}
这个例子的s增长速度为 2^t (2的t次方),时间复杂度为 log2n ( n对2的对数)
你的例子的s增长速度为 t^2 (t的平方), 时间复杂度为 n~1/2 ( n的开方)
ox_thedarkness 2006-01-02
  • 打赏
  • 举报
回复
orz .... 失败...错了,是log2n
上面的全是废话...
ox_thedarkness 2006-01-02
  • 打赏
  • 举报
回复
s = 1 +2 + 3 +。。。+ i = i*(i-1)/2 ~ i^2
即, s增长的速度是 i的平方
所以结果是 O ( s^1/2 ) 或者说复杂度为 s开方.

比较 log2n 和 n开方, 对他们的比值求极限,有

lim( n^1/2 / log2n )
= ln2* lim( n^1/2 / ln n )
= ln2* lim( (1/2)*(n^ -1/2 ) / (1/n) )
= (ln2)/2 * lim( n^ 1/2 ) -> 无穷

即, n开方是log2n的高阶无穷大, 简而言之就是比log2n差
YufengShi 2006-01-02
  • 打赏
  • 举报
回复
2^k = n (k是循环次数)

k = log2 n
也就是说复杂度是O(log2n)
jp1984 2006-01-02
  • 打赏
  • 举报
回复
and the bound is tight too
jp1984 2006-01-02
  • 打赏
  • 举报
回复
assume the loop run x times .
then s = 1 + 2 + .. + x = x(1+x)/2<n
2n>x(x+1)>x*x
=> x < sqrt(2n)
the basic operation takes O(1) time ,hence the procedure takes O(sqrt(n)) time
yangman211 2006-01-02
  • 打赏
  • 举报
回复
In my opinion of young brother,
the time complex of this question is O(n^2).

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧