GATE CS 2017 · Set-2 · Asymptotic Analysis & Recurrences

MCQ · 2 marks · Problem PROG-DIVC-0093

Consider the following C function:
int fun(int n) {
    int i, j;
    for (i = 1; i <= n; i++) {
        for (j = 1; j < n; j += i) {
            printf("%d %d", i, j);
        }
    }
}
The time complexity of fun in terms of \(\Theta\) notation is
  1. A
    \(\theta (n\sqrt{n})\)
  2. B
    \(\theta (n^{2})\)
  3. C
    \(\theta (n logn)\)
  4. D
    \(\theta (n^{2} logn)\)

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

Show the worked solution\[\boxed{\sum_{i=1}^{n}\left\lceil\frac{n-1}{i}\right\rceil\approx n\sum_{i=1}^{n}\frac1i=\Theta(n\log n)}\]For a fixed \(i\), \(j\) runs \(1,1+i,1+2i,\ldots\) while \(j<n\): about \(n/i\) iterations.Summing over \(i=1..n\) gives \(n\,H_n\approx n\ln n\) (harmonic series).Answer: C

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