GATE / CS ARCHIVE

GATE CSE 2006 / QUESTION 15

Value accumulated during repeated halving

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2006 paper

GATE 2006, Q15 1 mark · MCQ
Report issue

Control Flow & Loop Tracing

Question 15, GATE 2006: For positive integer n, the C fragment is: for (i=n,j=0; i>0; i/=2,j+=i); . Here i,j,n are integer variables and the loop body is empty. Which is the asymptotic value of j after termination, rather than the running time?
Options:
(A) Θ(log n)
(B) Θ(√n)
(C) Θ(n)
(D) Θ(n log n)
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. The update uses the comma operator: first integer-divide i by 2, then add the new i to j. For positive n, j=floor(n/2)+floor(n/4)+...=n−popcount(n).

2. It is at least floor(n/2) and less than n, hence Θ(n), C. This is the value accumulated, not the Θ(log n) iteration count.

3. Its value remains below n, so no positive signed overflow is needed when n is representable.

4. Teaching check: For n=13 the updates add 6,3,1,0, yielding j=10 even though there are only four iterations. Generally the sum lies between floor(n/2) and n, which supplies matching linear bounds without needing the exact popcount identity.

Original paper, page 2