GATE / CS ARCHIVE

GATE CSE 2015 SET 1 / QUESTION 64

GATE CSE 2015 Set 1 Q64

Algorithms · Asymptotic Analysis & Recurrences · Full GATE CSE 2015 Set 1 paper

GATE 2015 Set 1, Q64 2 marks · MCQ
Report issue

Asymptotic Analysis & Recurrences

Question 64, GATE 2015: 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 most closely approximates its return value? A n³; B n(log n)²; C n log n; D n log(log n).
Tap to enlarge
Your answer
Answer & solution

Official answer: D

The first inner loop computes p≈log₂n but never increments q. The second loop increments q for k=1,2,4,… below p, about log₂p times. Multiplying by n−1 outer iterations gives Θ(n log log n). This asks for the returned number, not running time: computing p itself costs Θ(log n) each iteration, so the code's runtime is Θ(n log n). Mathematical asymptotics assume integers do not overflow.

Solution: The outer loop runs n−1 times. Repeated integer halving of j from n until≤1 gives p=floor(log₂n). Doubling k from 1 while k<p increments q ceil(log₂p) times when p≥1. Thus for sufficiently large n the return value is(n−1)*ceil(log₂ floor(log₂n))=Θ(n log log n), D. This is the mathematical count under no-overflow arithmetic; q can overflow a fixed-width int for sufficiently large inputs.

Original paper, page 24 · Answer key