【问题标题】:How to prove an algorithm is Θ (log n) using summation notation?如何使用求和符号证明算法是 Θ (log n)?
【发布时间】:2017-02-12 21:45:32
【问题描述】:

假设我有以下代码:

int sum = 0;
int val=128;
for (int i=n; i>=1; i=i/2) {
    for (int j=1; j<val; j++) {
    sum ++;
    }
}

你如何证明这是数学上的 Θ(log n)?

我通常的方法是使用求和(sigma notation),但在这种情况下,我们不会线性增加循环变量。有什么好的方法呢?

【问题讨论】:

    标签: algorithm runtime asymptotic-complexity


    【解决方案1】:

    i 的值为n, n/2, n/4, ..., 1。由于它是整数,因此在此条件下其最终值为 1。假设n2^k,则迭代次数为k,即log n。因此情况没有改变,它是另一个具有一定迭代次数的for

    内部循环可以被认为是一条语句,因为val 是常量。

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 2011-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-01-20
      • 2015-08-29
      • 2021-11-03
      • 2010-12-09
      • 1970-01-01
      相关资源
      最近更新 更多