1 title description
The time complexity of the following program segment is
int sum = 0;
for(int i = 1; i < n; i *= 2)
for(int j = 0; j < i; j++)
sum++;
2 ideas
Observing the program, you can find thatthe number of executions of the inner layer is consistent with the number of executions of the outer layer, and the inner layer and the outer layer are "bundled" Relationship, in short, the outer layer is executed once and the inner layer is executed i times. So the final result is the time complexity of the inner layer.
The overall idea is to first find the number of executions of the outer layer, and then substitute it into the inner layer to calculate the final time complexity.
3 answers
Fayi
First recall the geometric sequence summation formula:
S = a 1 1 − q n 1 − q S=a_1\frac{1-q^n}{1-q } S=a11−q1−qnAmong thema1
Representative head, q
Representative common ratio,n
Number of numbers.
Back to this question, first observe the outermost for
cycle, the changing trend of i
is (wherek
Expressed as the k
th execution):
1 , 2 , 4 , 8 , . . . , 2 k − 1 1,2,4,8,. ..,2^{k-1} 1,2,4,8,...,2k−1Roughly obtained outer layer order:
2 k − 1 = n 2^{k-1}=n 2k−1=n k − 1 = l o g 2 n k-1=log_2n k−1=log2n k = l o g 2 n + 1 k=log_2n+1 k=log2n+1 ≈ log 2 n ≈log_2n ≈log2n
Next, find the time complexity of the inner layer. Since the number of executions of the inner layer is the same as the number of executions of the outer loop variablei
, then The changing trend of the execution times of the inner loop can be drawn: 1 , 2 , 4 , 8 , . . . , log 2 n 1,2,4,8,...,log_2n < /span>1,2,4,8,...,log2nChinese neck head1
,Kobi 为2
,Ichigo log_2n log2For the n term, substitute it into the geometric sequence summation formula to get: 1 ⋅ 1 − 2 l o g 2 n 1 − 2 1·\frac {1-2^{log_2n}}{1-2} 1⋅1−21−2log2n = 1 − n − 1 =\frac{1-n}{-1} =−11−n→ O ( n ) →O(n)→O(n)
Houji
Refer to method 1. The maximum value of j
in the inner layer is equal to the maximum value of i
, that is, 2 k − 1 2^{k-1} 2k−1, the most trips to the outer layer l o g 2 n log_2n log2n times [k
is the number of executions], write the formula:
∑ k = 0 l o g 2 n ∑ j = 0 2 k − 1 1 = ∑ k = 0 l o g 2 n 2 k + 1 = 1 − 2 l o g 2 ( n + 1 ) 1 − 2 = n + 1 − 1 \sum_{k=0} ^{log_2{n}}\sum_{j=0}^{2^{k-1}}1=\sum_{k=0}^{log_2{n}}2^{k+1}=\frac {1-2^{log_2({n+1)}}}{1-2}=n+1-1 k=0∑log2nj=0∑2k−11=k=0∑log2n2k+1=1−21−2log2(n+1)=n+1−1 = O ( n ) =O(n) =O(n)
Summarize
To put it simply, this question can also be thought of like this:
i=1, executed once,
i=2, executed 2 times,
i=4, executed 4 times, The result is obtained by summing the geometric sequence, which is the final time complexity i=2 to the kth power, indicating that a total of 2 to the kth power is executed ; …
I=8, executed 8 times,
The content is for reference only, please point out if there are any errors, thank you!