Question

Consider the following C function:

int fun1(int n) {
    int i, j, k, p, q = 0;
    for (i = 1; i < n; ++i) {
        p = 0;
        for (j = n; j > 1; j = j / 2)
            ++p;
        for (k = 1; k < p; k = k * 2)
            ++q;
    }
    return q;
}

Which one of the following most closely approximates the return value of the function fun1?

Choose one option
Official answer and solution
Official answer
D
From
Official GATE 2015 answer key

Solution

Trace the step counts of nested loops in terms of input size n.

Analyzing the nested loops of fun1(n):

  1. Outer loop: for (i = 1; i < n; ++i) executes n−1=Θ(n)n - 1 = \Theta(n) times.

  2. First inner loop: for (j = n; j > 1; j = j / 2) ++p;
    This loop repeatedly divides jj by 2 starting from nn until j≤1j \le 1.
    The number of iterations is p=⌊log⁡2n⌋=Θ(log⁡n)p = \lfloor \log_2 n \rfloor = \Theta(\log n).

  3. Second inner loop: for (k = 1; k < p; k = k * 2) ++q;
    This loop starts with k=1k = 1 and doubles kk until k≥pk \ge p.
    The number of increments to qq in one outer iteration is ⌊log⁡2p⌋=log⁡2(log⁡2n)=Θ(log⁡log⁡n)\lfloor \log_2 p \rfloor = \log_2(\log_2 n) = \Theta(\log \log n).

  4. Total return value:
    Summing qq over all nn iterations of the outer loop:

    q≈n×log⁡2(log⁡2n)=Θ(nlog⁡(log⁡n)).q \approx n \times \log_2(\log_2 n) = \Theta(n \log(\log n)).

This matches option D.

Final answer

D

Common trap

Confusing the doubling of kk with linear incrementation, which would erroneously yield nlog⁡nn \log n.

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

Source

Paper
GATE 2015 Computer Science and Information Technology (CS) Session 1
Question
41 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.