GATE / CS ARCHIVE

GATE CSE 1999 / QUESTION 17(b)

Prove population-count behavior

Computer Organization & Architecture · Instructions & Addressing Modes · Full GATE CSE 1999 paper

GATE 1999, Q17(b) 3 marks · Descriptive
Report issue

Instructions & Addressing Modes

Question 17(b), GATE 1999: For the same assembly with initial (R1,R2,R3)=(n,0,0), determine R3 on reaching Z:
X: CMP R1,0
   JZ Z
   MOV R2,R1
   SHR R1
   SHL R1
   CMP R2,R1
   JZ Y
   INC R3
Y: SHR R1
   JMP X
Z: ...
CMP sets comparison flags; JZ jumps on equality; MOV copies its second operand into its first; SHR/SHL shift by one bit.
Question 17(b), GATE 1999: For the same assembly with initial (R1,R2,R3)=(n,0,0), determine R3 on reaching Z:
X: CMP R1,0
   JZ Z
   MOV R2,R1
   SHR R1
   SHL R1
   CMP R2,R1
   JZ Y
   INC R3
Y: SHR R1
   JMP X
Z: ...
CMP sets comparison flags; JZ jumps on equality; MOV copies its second operand into its first; SHR/SHL shift by one bit.
Question 17(b), GATE 1999: For the same assembly with initial (R1,R2,R3)=(n,0,0), determine R3 on reaching Z:
X: CMP R1,0
   JZ Z
   MOV R2,R1
   SHR R1
   SHL R1
   CMP R2,R1
   JZ Y
   INC R3
Y: SHR R1
   JMP X
Z: ...
CMP sets comparison flags; JZ jumps on equality; MOV copies its second operand into its first; SHR/SHL shift by one bit.
Tap to enlarge
Answer & solution

Answer: R3=popcount(n), the number of 1 bits in n. (no official key was published)

For nonnegative integer n (or an unsigned fixed-width register with logical SHR), write current R1=2k+b, where b∈{0,1}. SHR then SHL yields 2k, so CMP detects inequality exactly when b=1; R3 therefore increases by b. The SHR at Y sets R1=k. After t iterations, R1=floor(n/2t) and R3 equals the number of ones in the t low-order bits removed from n. This invariant holds initially and is preserved by the decomposition 2k+b. Termination occurs when R1=0, after all significant bits have been examined, so R3 is the binary population count of n. For n=0 the initial branch exits immediately and R3=0. For negative signed inputs the outcome requires a specified word width and right-shift convention; arithmetic SHR is not covered by this nonnegative-integer proof.

Original paper, page 8