1,444 views
1 votes
1 votes

Consider the following code fragment 

      

for i=1 to n/2 do
    for j=i to n-1 do
        for k=1 to j do
            output ''foobar''

Assume $n$ is even Let $T(n)$ denote the number of times 'foobar' is printed as a function of $n$.

  1. Express $T(n)$ as three nested summations.
  2. Simplify the summation. Show your work.

3 Answers

Best answer
2 votes
2 votes
a. $T(n) = \sum_{i=1}^{n/2} \sum_{j=i}^{n-1} \sum_{k=1}^{j} 1$

The 1 is used for constant no. of operations. We can also use $c$ for it.

b. $\sum_{i=1}^{n/2} \sum_{j=i}^{n-1} \sum_{k=1}^{j} 1\\= \sum_{i=1}^{n/2} \sum_{j=i}^{n-1} j\\= \frac{1}{2} \sum_{i=1}^{n/2} (n-1)n - i(i-1) \\= \frac{1}{2} \sum_{i=1}^{n/2} n^2-n - i^2-i $

We need not solve further as the first term itself gives our answer which is $ \frac{n^3}{4}=\Theta\left( n^3\right).$  

PS: In the summation formula for the sum of first $n$ natural numbers $\left( \frac{n.(n+1)}{2} \right)$ and the sum of the squares of first $n$ natural numbers $\left( \frac{n.(n+1).(2n+1)}{6} \right)$ are used.
edited by
0 votes
0 votes
I guess

T(n)  = O(nlogn)

1st loop runs for log n times

2nd loop for log n times

3rd loop for n times
edited by
0 votes
0 votes
o(n^3).you can easily get a lower tringular matrix by first two loops and 3rd loop is adding another dimension.so its o(n^3).

this type of analysis is not the best method.

Related questions

129
views
1 answers
2 votes
SSR17 asked Apr 25
129 views
for (i = 1; i <= N; i++){ for (j= 1;j <= i^2;j=j+i){ //some code}} how is this O(n^2)? explain in detail and simple terms
420
views
1 answers
0 votes
Overflow04 asked Oct 9, 2022
420 views
how O($n^{2}$) in the last.(in the given solution).
300
views
0 answers
0 votes
Overflow04 asked Oct 9, 2022
300 views
Is it really coping operation will take O(n).Does copy is done character by character.means simple code like (in c++) for(int i=0;i<n;i++){s=s;}will take O($n^{2}$)