GATE / CS ARCHIVE

GATE CSE 2017 SET 2 / QUESTION 38

GATE CSE 2017 Set 2 Q38

Algorithms · Asymptotic Analysis & Recurrences · Full GATE CSE 2017 Set 2 paper

GATE 2017 Set 2, Q38 2 marks · MCQ
Report issue

Asymptotic Analysis & Recurrences

Question 38, GATE 2017: For positive n, C code executes: for(i=1;i<=n;i++){ for(j=1;j<n;j+=i){ printf(" %d %d",i,j); } }. Find its Θ time complexity, treating each iteration/output as unit cost. A:Θ(n√n). B:Θ(n²). C:Θ(n log n). D:Θ(n² log n).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

1. Fix i. The inner-loop j values are 1,1+i,1+2i,… below n, so there are ceil((n-1)/i) iterations. The step size is i, not 1; different outer-loop iterations therefore have different costs.

2. Sum over i=1,…,n. Ignoring rounding gives (n-1)Σ1/i=(n-1)Hn. Rounding adds at most n operations, and Hn=Θ(log n), so the total is Θ(n log n).

3. The outer-loop overhead is only Θ(n) and does not change the result, giving C. This is the conventional unit-cost model used by the question. Counting the individual decimal digits written by printf, or fixed-width integer overflow at extreme n, would be a different analysis from the intended asymptotic loop count.

Original paper, page 14 · Answer key