问题
I have been thinking over this problem for a few days now and am hung up on calculating the number of times the second nested for-loop will run. I believe that I have the correct formula for determining the running time for the other two for-loops, but this third one has me hung up. I have the first loop running n-1 times. The equation to determine the number of times loop #2 runs is; The summation of 1 to n-1. If anyone could help me understand how to find the number of times loop #3 runs it would be greatly appreciated.
for ( int i=1; i<=n-1; i++ ) {
for ( int j=i+1; j<=n; j++ ) {
for ( int k=1; k<=j; k++ ) {
}
}
}
回答1:
The third loop runs C times:
C = Sum( Sum ( Sum ( 1 , k = 1 .. j ) , j = i+1 .. n ) , i = 1 .. n-1 )
= Sum( Sum ( j , j = i+1 .. n ) , i = 1 .. n-1 )
= 2 + 3 + 4 + ... + n
+ 3 + 4 + ... + n
...
+ n
= 2*1 + 3*2 + 4*3 + 5*4 + ... + n*(n-1)
= (1*1 + 1) + (2*2 + 2) + (3*3 + 3) + ... + ((n-1)*(n-1) + n-1)
= (1^2 + 2^2 + ... (n-1)^2) + (1 + 2 + 3 + ... + (n-1))
= (n-1)*n*(2*n-1)/6 + (n-1)*n/2
= (n-1)*n*(2*n+2)/6
= O(n^3)
Here I used the formulas:
1^2 + 2^2 + ... + m^2 = m*(m+1)*(2*m+1)/6
and
1 + 2 + ... + m = m*(m+1)/2
来源:https://stackoverflow.com/questions/7375296/trouble-with-nested-for-loop-running-time