The GATE Grind

GATE 2017 CS (CS2) – Question 48

Algorithms · Asymptotic Analysis and Time/Space Complexity · 2 marks · Multiple choice

Find the time complexity.

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);
        }
    }
}
  1. $\Theta(n\sqrt n)$
  2. $\Theta(n^2)$
  3. $\Theta(n\log n)$
  4. $\Theta(n^2\log n)$

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (C) $\Theta(n\log n)$

Explanation

For each i, the inner loop takes Θ(n/i) iterations, up to constant endpoint effects. Summing over i gives $\Theta(n\sum_{i=1}^n1/i)=\Theta(nH_n)=\Theta(n\log n)$. Thus C; the increasing step size prevents quadratic work.

More Asymptotic Analysis and Time/Space Complexity questions

All Asymptotic Analysis and Time/Space Complexity questions →