简体   繁体   English

一个简单的 while 循环的时间复杂度

[英]Time complexity of a simple while loop

I am confused as to the time complexity of this code.我对这段代码的时间复杂度感到困惑。

int a = 1;

while ( a < n ) {
  a = a * 2;
}

I am new to time complexities我是时间复杂度的新手

It's log(n).这是日志(n)。 If n is 4, the loop executes 2 times.如果n为 4,则循环执行 2 次。 If n is 8, the loop executes 3 times.如果n为 8,则循环执行 3 次。 If n is 16, the loop executes 4 times.如果n为 16,则循环执行 4 次。

That's a logarithmic relationship, not a linear one.这是一种对数关系,而不是线性关系。

If you check for the values a can get you will see:如果您检查a can get 的值,您将看到:

1, 2, 4, 8, 16, 32, ..., 

and the iterations will continue until a is smaller than n , which means that the number of iterations is bounded by ⌈log2(n)⌉ .并且迭代将继续,直到a小于n ,这意味着迭代次数受⌈log2(n)⌉限制。

You can thus conclude that the time complexity is logarithmic in n .因此,您可以得出结论,时间复杂度在n中是对数的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM