GATE CS 2015 · Set-1 · Asymptotic Analysis & Recurrences

MCQ · 2 marks · Problem PROG-DIVC-0104

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

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

Show the worked solution\[\boxed{q\approx(n-1)\cdot\log_2 p,\qquad p\approx\log_2 n}\]For each \(i\), the \(j\)-loop halves \(n\) down to 1, so \(p\approx\log_2 n\).The \(k\)-loop doubles \(k\) up to \(p\), so it adds about \(\log_2 p\approx\log_2\log_2 n\) to \(q\).Over \(n-1\) values of \(i\): \(q\approx n\log\log n\).Answer: D

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