时间复杂度为(i = 3; i <= n; i = i * 2)

时间:2013-12-13 17:20:43

标签: algorithm time-complexity

时间复杂度

for(i=3; i<=n; i=i*2)
    x++;

是(log(n / 3)+1)。我想知道为什么?

2 个答案:

答案 0 :(得分:4)

您将从i=3(给定)开始并一直迭代到i>n(给定)。对于每次迭代,索引计数器i加倍(给定)。

因此,迭代次数将是您可以将值加倍的次数,初始值为3(给定)。

因此,循环将在3*2^k>n时终止。为了解决时间复杂度k,我们将先前的计算减少到:

LET: k,n ∈ Z+ (k,n are positive integers)
==> log(3*2^k)        > log(n)          (given)
==> log(3) + log(2^k) > log(n)          (logarithmic expansion)
==> log(3) + k*log(2) > log(n)          (logarithmic expansion)
==>          k*log(2) ~ log(n)          (removing added constants)
==> k                 ~ log(n) / log(2) (linear operation)
==> k                 ~ log(n - 2)      (logarithmic refactoring)
==> k                 ~ log(n)          (removing added constants)

因此,k最接近的复杂性为log(n),因为常量被排除在通用复杂度计算之外。

如果你想从上面得到确切的步数/迭代次数:

LET: k,n ∈ Z+ (k,n are positive integers)
==> log(3*2^k)        ~ log(n)            (given)
==> log(3) + log(2^k) > log(n)            (logarithmic expansion)
==> log(3) + k*log(2) > log(n)            (logarithmic expansion)
==> k*log(2)          > log(n) - log(3)   (linear refactoring)
==> k*log(2)          > log(n/3)          (logarithmic refactoring)
==> k                 > log(n/3) / log(2) (linear refactoring)

+1基本上用于对操作数进行舍入,因为k不太可能是整数,因此我们至少需要ceiling(k)次操作才能完成。因此,确切的步数变为(log(n/3)+1)/log(2)

是否有解释为什么log(2)被排除在解决方案之外?如果您正在寻找特定的迭代次数而不是一般情况(即:大写符号)?

答案 1 :(得分:0)

查看these slides的最后一页。

具体是:

enter image description here