【问题标题】:For Loops Time ComplexityFor 循环时间复杂度
【发布时间】:2019-06-16 18:42:44
【问题描述】:

对于给定的代码,Big-O 表示法的时间复杂度是多少?

for(int i = 1; i <= n; i++)
    for(int j = 1; j <= n; j = j + i)
             some_constant_statement

如果我没记错的话

First loop take  n times
Second loop n.long(n) time
For Second loop :

n + n/2 + n/3 + n/4 +...................n/n times
n(1 + 1/2 + 1/3 + ..............1/n) times means
n(long(n)) time
So, time complexity of entire piece of code is n.n.long(n)

如果我错了,请纠正我。

【问题讨论】:

  • H.Das,您的推理是正确的,只是您不必计算第一个循环,因为您在计算第二个循环的操作数时已经考虑到了它。它是 O(nlogn)
  • 感谢您的指正!!所以时间复杂度是n.log(n)
  • 链接的副本不是副本,因为内部循环的增量是1,而不是i。

标签: data-structures time-complexity big-o


【解决方案1】:

简答:时间复杂度为O(n log n)。

内循环每次都需要 n 步。确实:

for(int j = 1; j <= n; j = j + i)
         some_constant_statement

这里的j 总是从1(含)迭代到n(含),所以这将执行n/i 常量语句。

因此,操作的总数为:

    n
   ---
   \     1
n  /    ---
   ---   i
   i=1

总和是Harmonic series [wiki]。我们可以用Stirling's approximation [wiki] 来近似这个。因此我们知道:

     n                  n
    ---                ---
    \     1            \    1
    /    ---  ≤ ln n ≤ /   ---
    ---  i+1           ---  i
    i=1                i=1

这意味着我们可以说操作的总数具有时间复杂度O(n×ln n)。由于 loga(b) = log a/log b,我们可以将其表述为 O(n log n) em>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2015-02-16
    • 2013-09-13
    • 1970-01-01
    相关资源
    最近更新 更多