The GATE Grind

GATE 2011 CS (CS1) – Question 59

Programming and Data Structures · Recursion · 2 marks · Multiple choice

Find foo(513,2).

unsigned int foo(unsigned int n, unsigned int r) {
    if (n>0) return (n%r)+foo(n/r,r);
    else return 0;
}
  1. 9
  2. 8
  3. 5
  4. 2

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (D) 2

Explanation

The function sums binary digits, the population count. Since 513=512+1=2⁹+1, its binary representation has exactly two one bits. The return value is two, D.

More Recursion questions

All Recursion questions →