In: Computer Science
for (i=0; i<n; i++) //loop 1
for (j=1; j<n; j=j*2) //loop 2
for (k=0; k<j; k++) //loop 3
... // Constant time operations
end for
end for
end for
Loop1 executes from 0 to N-1, therfore we can say that loop1 executes for N times
Lets investigate loop2 and loop3 together as loop3 is dependent on loop2 iteration variable j
When j = N, loop3 executes N times
When j = N/2, loop3 executes N/2 times
When j = N/4, loop3 executes N/4 times
When j = j, loop3 executes N/2j times
so on ...
So the total number of times loop3 runs = N + N/2 + N/4 + N/8 + ...
=> N * (1 + 1/2 + 1/4 + 1/8 ... )
The co-efficient of N is (1 + 1/2 + 1/4 + 1/8 ... ) which is in geometric progression with common ratio r = 1/2 (< 1)
Therefore (1 + 1/2 + 1/4 + 1/8 ... ) = N/(1 - 1/2) = N/(1/2) = 2*N (since GP sum = a/(1-r))
Therefore total time complexity of loop2 and loop3 combined = O(N)
Therefore total time complexity of this code is O(N * N) = O(N2)
T(N) = O(N2)