GATE / CS ARCHIVE

GATE CSE 2011 / QUESTION 49

Recursive sum of binary digits

Programming in C · Recursion · Full GATE CSE 2011 paper

GATE 2011, Q49 2 marks · MCQ
Report issue

Recursion

Question 49, GATE 2011: Consider unsigned int foo(unsigned int n, unsigned int r) { if (n>0) return ((n%r)+foo(n/r,r)); else return 0; }. What does foo(513,2) return?

(A) 9
(B) 8
(C) 5
(D) 2
Question 49, GATE 2011: Consider unsigned int foo(unsigned int n, unsigned int r) { if (n>0) return ((n%r)+foo(n/r,r)); else return 0; }. What does foo(513,2) return?

(A) 9
(B) 8
(C) 5
(D) 2
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Step through it (23 steps)

The function sums the base-r digits of n. Since 513=512+1=29+1, its binary representation is 1000000001 and has two 1 bits. Consequently foo(513, 2)=2, option D. All intermediate recursive divisions are unsigned integer divisions and terminate at zero.

The successive n values are 513,256,128,64,32,16,8,4,2,1,0. Remainders modulo 2 are 1 at n=513 and n=1 and zero at every other positive step. Summing them produces 2. The exponent 9 tells where the highest bit lies, not how many set bits there are; similarly, the number of recursive positive calls is 10, not the return value. The function counts ones for base 2 because binary digits can only be zero or one.

Original paper, page 14 · Answer key