GATE CS 2013 · Asymptotic Analysis & Recurrences

MCQ · 2 marks · Problem PROG-DIVC-0110

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
  1. A
    \(\Theta (n^{2})\)
  2. B
    \(\Theta (n^{2}logn)\)
  3. C
    \(\Theta (n^{3})\)
  4. D
    \(\Theta (n^{3}logn)\)

Solve it on GATE DA practice →More Searching & Sorting Algorithms problems

Show the worked solution\[\boxed{k=\underbrace{\left(\tfrac n2+1\right)}_{i\text{-loop}}\cdot\underbrace{\lfloor\log_2 n\rfloor}_{j\text{-loop}}\cdot\frac n2}\]The outer loop runs about \(n/2\) times; the inner loop doubles \(j\) from 2 to \(n\), about \(\log_2 n\) times; each inner iteration adds \(n/2\).\[k\approx\frac n2\cdot\log_2 n\cdot\frac n2=\Theta(n^2\log n).\]Answer: B

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com