这个循环的大O复杂性

时间:2014-06-01 16:00:24

标签: big-o time-complexity

如果我有

int i;
for(i = 1; i < n; i *= 2) //n is the size of an array passed to the function
{
  //O(1) code here
}

Big O复杂性是什么? “i * = 2”位让我很困惑。我尝试了操作计数,但现在我更加困惑。

4 个答案:

答案 0 :(得分:3)

它看起来像是O(log(n)),因为你不是在整个序列上迭代,而是使用两个幂的步骤。

答案 1 :(得分:1)

复杂度为O(log 2 (N))

基本上你的&#39;我&#39;每次迭代加倍,所以在1次迭代之后它是2,然后是4,然后是8.所以如果n = 2 8 那么循环将重复(大致)8次。

答案 2 :(得分:1)

每次都要将步骤减半,所以最终得到O(log n),其中n是迭代总数。请参阅:What would cause an algorithm to have O(log n) complexity?

答案 3 :(得分:1)

复杂性为O(log n)

您可以将循环重写为 for(x = 0; pow(2,x) < n; x++) x < log n pow。 (2x应计算{{1}})

相关问题