【问题标题】:Example algorithm time complexity示例算法时间复杂度
【发布时间】:2014-11-21 11:42:02
【问题描述】:

我最近了解了 Big Oh 符号。我最近遇到了书中给出的例子。

void Function(int n)
{
int i=1 ;
int s=1 ;
while( s <= n)
{
i++ ;
s= s+i ;
print(\*");
}
}

不知道作者是怎么得出上述算法的时间复杂度为O(√n)的。我只是想了解得出这个结论的过程?

【问题讨论】:

    标签: time complexity-theory time-complexity


    【解决方案1】:

    它很容易被视为s is growing quadratic in terms of number of iteration

    s = 1 // set as 1 initially 现在我们添加S = s + i // Where i increasing linearly by one unit in each iteration

    //So it's just a addition i.e. s = 1 + 2 + 3 +4 ....+i, which will sum up to s = i(i+1)/2 因此s = i(i+1)/2 = (i^2+i)/2 其中 i 是迭代次数。

    现在,在i 迭代中,我们得到s = (i^2+i)/2 要获得s &gt;=n,我们只需要√n 迭代。 因此给定程序的时间复杂度将是O(√n)

    【讨论】:

    • 我不明白你如何识别 s=i(i+1)/2 ?有没有需要为此阅读的数学主题?怎么变成 O(√n)。抱歉问了太多问题,但我正在尽我所能理解时间复杂度分析。
    • 我已经编辑了答案,看看你能不能看懂。
    • 感谢 Shravan。我知道你是如何得到这个表达式 s=(i^2+i)/2 的。但我不明白它是如何变成 O(√n) 的。再次为吃掉你的脑袋道歉。
    • @Beast 所以 s=(i^2+i)/2 并且你想要 s=>n 与 (i^2+i)/2 >=n 相同。请注意,i 表示循环将执行的次数,因为您每次将其增加 1。 (i^2+i)/2 >=n 不等式是二次的,并且(为简单起见)您可以将其简化为 i^2>=n => i>=√n。
    • 如果您了解数学的基本概念,例如 A.p、G.P、递归、对数和多项式函数,我会说不。如果你真的想要什么,你可以看看这本书cs.princeton.edu/courses/archive/fall07/cos433/mathcs.pdf
    猜你喜欢
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 2013-12-31
    • 1970-01-01
    相关资源
    最近更新 更多