find the complexity for loop

98 Views Asked by At

what is the time complexity T(n) of the following potion of the code? for simplicity you may assume that n is power of 2. that is n=2^k . for some positive integer k.

for(i=1;;I<=n;i++)
  for(j=n/2;j<n;j++)
      print x;

choose the correct answer:

  1. T(n)=n+1
  2. T(n)=n^2+2n
  3. T(n)=n
  4. T(n)=n^3
  5. T(n)=n(n/2 +1)
1

There are 1 best solutions below

0
On

So lets write some iterations:

i           j
1           0       to n-1
2           1       to n-1
3           1       to n-1
4           2       to n-1
5           2       to n-1
.
.
.
n-2         (n-2)/2 to n-1  
n-1         (n-2)/2 to n-1  
n           n/2     to n-1

Now lets remember 1st and nth and calculate sum of ranges(end - start + 1) from i = 2 till i = n-1.

S = (n-1 - 1 + 1) + (n-1 - 1 + 1) + (n-1 - 2 + 1) + (n-1 - 2 + 1) + ...  + (n-1 - (n-2)/2 + 1) + (n-1 - (n-2)/2 + 1)

...

S = (n - 1) + (n - 1) + (n - 2) + (n - 2) + ...  + (n - (n-2)/2) + (n - (n-2)/2)

...

S = 2*(n - 1) + 2*(n - 2) + ... + 2*(n - (n - 2)/2)

...

S = 2*((n - 1) + (n - 2) + ... + (n - (n - 2)/2))

...

S = 2*(n*(n-2)/2 - (1 + 2 + 3 + ... + (n - 2)/2 ))

...

Last is arithmetic progression which is calculated by formula:

N*(A1 + A2)/2

where:

N = (n - 2)/2,      A1 = 1,      A2 = (n - 2)/2 

So we end up with:

1 + 2 + 3 + ... + (n - 2)/2 =  n*(n - 2)/8

...

S = n^2 - 2*n - 2*(n*(n - 2)/8)

...

S = n^2 - 2*n - n*(n - 2)/4

Now lets add 2 values that we remembered:

S = n + n/2 + n^2 - 2*n - n*(n - 2)/4

...

S = (4*n + 2*n + 4*n^2 - 8*n)/4 - n*(n - 2)/4

...

S = (4*n + 2*n + 4*n^2 - 8*n - n^2 + 2*n)/4

...

S = (3/4)*n^2

I am getting none of the above. I have checked and rechecked but can not find the error.