3嵌套循环的复杂性

时间:2019-03-20 13:24:57

标签: algorithm time-complexity big-o complexity-theory

int x = 0;
for (int i = n; i >= 3; i--) {
    for (int j = 1; j <= Math.log(i) / Math.log(2); j++) {
        for (int t = 0; t <= n; t += j) {
            x++;
        }
    }
}
System.out.println(x);

如您所见,我有3个for循环,其条件相互依赖。

我的分析

  • 第一个循环:我假设它将运行(n-2)次“最坏情况”的情况。
  • 第二个循环:我假设它将运行log(n)次“最坏情况”的情况。
  • 第三个循环:我假设它将运行(n)次“最坏情况”的情况。

所以我计算出3个循环的功能将是: (n-2)*(log(n))*(n)=(n^2)*log(n)-(2n)*log(n) = O((n^2)*log(n))

我不确定我的计算是否正确,请务必告知!

1 个答案:

答案 0 :(得分:3)

在处理条件相互依赖的多个嵌套循环时必须小心。简单地将它们的复杂性相乘可能会导致错误的结果。


  • 内循环

    这大约运行n / j次。精确值为floor([n + 1] / j)

  • 中间循环

    这大约运行log2(i)次。 j的精确范围是[0, floor(log2(i))]

  • 外循环

    这可以在不影响时间复杂度的情况下反转,即(int i = 3; i <= n; i++)

将以上内容合并为一个总和:

enter image description here


数学笔记:

  • 四舍五入的数字与其原始值仅相差小于1,即:

    enter image description here

  • 1 / j的总和是Harmonic Series,其渐近表达式为:

    enter image description here

  • Stirling's approximationlog(n) + log(n-1) + log(n-2) + log(n-3) + ... = O(n log n)

应用以上内容:

enter image description here


因此:

enter image description here

内积表达式的渐近复杂度是什么–

log(3) * log(4) * log(5) * ... * log(n)吗?

上限由log(n)增大为项数的幂,即log(n)^(n-2)

enter image description here

与直接乘以最坏情况的复杂度O(n^2 log n)所得的结果不同。

相关问题