【问题标题】:Big O Time Complexity for this code此代码的大 O 时间复杂度
【发布时间】:2014-03-23 04:20:35
【问题描述】:

给定以下代码-:

for(int i = 1; i <= N; i++)
    for(int j = 1; j <= N; j = j+i)
    {
        //Do something
    }

我知道外循环运行N 次,而内循环运行大约log(N) 次。这是因为在 ij 的每次迭代中运行 ceil(N)ceil(N/2)ceil(N/4) 次等等。这只是一个粗略的计算,通过它可以猜测时间复杂度肯定是O(N log(N))

我如何在数学上证明相同?

我知道对于 i<sup>th</sup> 迭代,j 递增 ceil(N/2<sup>(i - 1)</sup>)

【问题讨论】:

  • 您可能喜欢使用我在 myanswer 中使用的方法:A puzzle related to nested loops,但这需要时间。
  • @Alp j 每次迭代都会增长 i,而不是 1。
  • 不确定但可能会有所帮助:what is value of x in term of n? 这是one more question
  • @GrijeshChauhan:这个例子很好,但我正在寻找一个合适的数学证明,我会将log 应用于基数 2。
  • 也许我在考虑迭代递归求解,这里显然不能应用。

标签: big-o time-complexity pseudocode


【解决方案1】:

每个 i 值的内循环的总迭代次数将是

i = 1: j = 1, 2, 3 ..., n ---> total iterations = n
i = 2: j = 1, 3, 5 ..., n ---> total iterations = n/2 if 2 divides n or one less otherwise
i = 3: j = 1, 4, 7 ..., n ---> total iterations = n/3 if 3 divides n or one less otherwise
...
i = m: j = 1, 1 + m, ... , n ---> total iterations ~ n/m
...
1

所以大约总迭代次数为(n + n/2 + n/3 ... + 1)

该总和是Harmonic Series,其值约为ln(n) + C,因此总迭代次数约为n ln(n),并且由于所有对数都由一个常数相关,因此迭代次数将为O(nlogn)

【讨论】:

  • 这正是我想要的。谢谢!
  • @TheRedBlackTree 你说得对,n(n + ... + 1) 太多了。感谢您接听!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-06
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
  • 2018-07-08
  • 2014-05-29
  • 2021-08-30
相关资源
最近更新 更多