[英]Calculating the Time Complexity of nested loop with logarithmic increase
I am learning at my own pace online. 我正在以自己的速度在线学习。 I was solving some examples but I can't wrap my mind around this one:
我正在解决一些例子,但我不能围绕这个例子:
while(i<n)
{
for(int j=1; j<=i; j++)
sum = sum + 1;
i *=2;
}
I think the answer should be 2^n but my friend says nlog(n) 我认为答案应该是2 ^ n,但我的朋友说nlog(n)
Can someone find the big-O for this loop and explain to me how to do so? 有人能找到这个循环的大O并向我解释如何这样做吗?
The outer loop will enter it's body log2(n)
times, because i
is increasing exponentially and thereby reaches the end n
faster and faster. 外循环将进入它的主体
log2(n)
次,因为i
以指数方式增加,从而越来越快地到达结束n
。 For example, if n
were 1024
, it would need only 10 iterations, with n=65536
, it were 16 iterations. 例如,如果
n
为1024
,则只需要10次迭代, n=65536
,这是16次迭代。 The accurate count is log2(n)
, but in terms of runtime complexity the logarithmic behaviour is enough. 准确计数是
log2(n)
,但就运行时复杂性而言,对数行为就足够了。 So here the complexity is O(log(n))
. 所以这里的复杂性是
O(log(n))
。
The inner loop for(int j=1; j<=i; j++)
, each time when evaluated, will run to the corresponding i
. 每次评估时,
for(int j=1; j<=i; j++)
的内部循环将运行到相应的i
。 It can be shown that the average run width is about n / log2(n)
, since i
is 1
, 2
, 4
, ... n
with log2(n)
steps. 可以示出的是平均运行宽度是大约
n / log2(n)
,因为i
是1
, 2
, 4
,... n
与log2(n)
步骤。 For example, if n
is 31
, i
is 1
, 2
, 4
, 8
, 16
, the sum is 31
with 5
steps. 例如,如果
n
是31
, i
是1
, 2
, 4
, 8
, 16
,总和为31
与5
步骤。 So it is permissible to take complexity O(n/log(n))
here. 所以这里允许采用复杂度
O(n/log(n))
。
The overal complexity is then O(log(n)*n/log(n))
, which is O(n)
. 然后,总复杂度为
O(log(n)*n/log(n))
,即O(n)
。
We can assume without loss of generality that N
is equal to 2^k + 1
. 我们可以假设
N
等于2^k + 1
而不失一般性。 We need to find the number of iterations of the inner loop. 我们需要找到内循环的迭代次数。 There will be
k
iterations of outer loop with 2^0, 2^1, ..., 2^k
iterations of the inner loop. 将存在
k
次迭代的外循环,其具有内循环的2^0, 2^1, ..., 2^k
次迭代。 Let's sum up this values. 让我们总结一下这个值。
It's n
. 这是
n
。
if n=2^k
then while complexity is k, 如果
n=2^k
那么复杂度是k,
second loop : 2^1 + 2^2 + ... 2^k = 2^(k+1)-1 ~= 2^(k+1)
第二个循环:
2^1 + 2^2 + ... 2^k = 2^(k+1)-1 ~= 2^(k+1)
2^(k+1) = 2*n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.