Question

Consider the following function:

int unknown(int n){
    int i, j, k=0;
    for (i=n/2; i<=n; i++)
        for (j=2; j<=n; j=j*2)
            k = k + n/2;
    return (k);
}

The return value of the function is

Choose one option
Official answer and solution
Official answer
B
From
Official GATE 2013 answer key

Solution

Count the number of iterations of the nested loops and sum the incremental updates to variable k.

Let us analyze the loops in unknown(int n):

  1. Outer loop: for (i = n/2; i <= n; i++)
    The index ii ranges from n/2n/2 to nn. The number of iterations is:

    (n−n/2+1)=Θ(n)(n - n/2 + 1) = \Theta(n)
  2. Inner loop: for (j = 2; j <= n; j = j * 2)
    The index jj takes values 2,4,8,16,…,2⌊log⁡2n⌋2, 4, 8, 16, \dots, 2^{\lfloor \log_2 n \rfloor}.
    The number of iterations is ⌊log⁡2n⌋=Θ(log⁡n)\lfloor \log_2 n \rfloor = \Theta(\log n).

  3. Loop body: k = k + n/2;
    This statement executes for each combination of the outer and inner loop iterations:

    Total executions=Θ(n)×Θ(log⁡n)=Θ(nlog⁡n)\text{Total executions} = \Theta(n) \times \Theta(\log n) = \Theta(n \log n)

    In each execution, the value added to kk is n/2=Θ(n)n/2 = \Theta(n). Since kk starts at 0, the final value returned is:

    k=∑iterationsn2=Θ(nlog⁡n)×Θ(n)=Θ(n2log⁡n)k = \sum_{\text{iterations}} \dfrac{n}{2} = \Theta(n \log n) \times \Theta(n) = \Theta(n^2 \log n)

Thus, the return value of the function is Θ(n2log⁡n)\Theta(n^2 \log n).

Final answer

B

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2013 Computer Science and Information Technology (CS)
Question
31 of 65, printed as CS Q.31
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.