Consider the first piece of code,
for(i=n ; i>1 ; i/=2) //for any size n { for(j = 1; j < i; j++) { x+=a } }
The instruction x+=a is executed a total of n + n/2 + n/4 + ... + 1 times.
The sum of the first log 2 n members of GP with the initial term n and the common ratio 1/2 is (n (1- (1/2) log 2 n )) / (1/2) . Thus, the complexity of the first code fragment is O (n) .
Now consider the second piece of code,
for(i=1 ; i<=n; i++,x=1) { for(j = 1; j <= i; j++) { for(k = 1; k <= j; x+=a,k*=a) { } } }
The two outer loops together name the innermost cycle in the sum n(n+1)/2 times. The innermost loop runs no more than log<sub>a</sub>n times. Thus, the total time complexity of the second code fragment is O (n 2 log a n) .
Deepu source share