这个while循环的时间复杂度是多少?

时间:2016-06-26 11:50:22

标签: c while-loop time-complexity

while(n>x) 
  x*=x;

正确的答案是log(log(n)),我可以看到log(n),因为x ^ k> = n是while循环停止的时候。所以我得登录(n),我错过了什么?

P.S:给出x = 2。

4 个答案:

答案 0 :(得分:5)

设a为x的原始值,并假设a> 1。

  • 在第一个循环之后,x = a ** 2
  • 在第二个循环之后,x = a ** 4
  • 在第三个循环之后,x = a ** 8
  • ...在第k个循环之后,x = a **(2 ** k)

x> = n表示

a**(2**k) >= n
2**k >= log(n)/log(a)
k >= log2(log(n)/log(a)) = log2(log(n))-log2(log(a))

答案 1 :(得分:4)

展开循环(让x = 2),你会看到:

  x =     2 
  x =     4 //   2 * 2
  x =    16 //   4 * 4
  x =   256 //  16 * 16 
  x = 65536 // 256 * 256
  ... 
  x = 2 ** (2 ** n) // you can prove this by induction

等等

  n = log(log(x))

如果您拥有n = log(x)正文,则x *= constant进行估算是完全正确的。我们有constant == 2

  x = 2
  x = 4
  x = 8
  ...
  x == 2 ** n 

其中n只是

  n = log(x) 

答案 2 :(得分:3)

x起始值为a> 1。每次x的值都是a的指数,每次指数加倍,因为每次迭代都是平方数。

因此m'项由enter image description here给出,其中m是执行的循环数。因此,我们需要enter image description hereenter image description here,这确实是enter image description here

答案 3 :(得分:0)

修改:(Given x = 2)

如果符合以下条件,您的回答是正确的:

while(n>x) 
  x*=2;

这意味着达到结果的时间每次迭代减少一半

但由于每次迭代时间缩短xx正在增加,您将获得O log(Log(n))

Log(n)是每次迭代跳过一半的复杂性(B-Tree)。