Common data questions

Common Data for Questions 48 and 49:

Consider the following recursive C function that takes two arguments.

unsigned int foo(unsigned int n, unsigned int r) {
    if (n > 0) return ((n % r) + foo(n / r, r));
    else return 0;
}

Shared with question 48.

Question

What is the return value of the function foo when it is called as foo(513, 2)?

Choose one option
Official answer and solution
Official answer
D
From
Official GATE 2011 answer key

Solution

Trace the recursive function execution for base 2.

  1. Calling foo(n, 2) computes the sum of the binary bits (the Hamming weight or number of set bits) of nn.
  1. Represent n=513n = 513 in binary:
513=512+1=29+20=(1000000001)2513 = 512 + 1 = 2^9 + 2^0 = (1000000001)_2
  1. The binary representation of 513 contains exactly two 1s and eight 0s.
  1. Summing all binary digits yields 1+1=21 + 1 = 2.
Final answer

D

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2011 Computer Science and Information Technology (CS)
Question
49 of 65, printed as CS Q.49
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.