Skip to content
Official PYQ · 2011

GATE CS 2011 Q49 — Algorithm Design: Dynamic Programming

Explain with AI

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;
}

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

Choose one option
View worked solution

Answer: D

The given recursive function foo(n, r) computes the sum of the digits of the number nn when represented in base rr.

Analysis of the Function

  • n % r extracts the least significant digit of nn in base rr.
  • n / r performs an integer division, effectively shifting nn to the right by one digit in base rr.
  • The recursion terminates when n=0n = 0, returning 00.

Therefore, foo(n, r) returns the sum of the digits of nn in base rr.

Calculation for foo(513, 2)

Here, n=513n = 513 and r=2r = 2 (binary representation).

We express 513513 in binary (base 2):

513=512+1=29+20=(1000000001)2513 = 512 + 1 = 2^9 + 2^0 = (1000000001)_2

The sum of the binary digits (the number of set bits) is:

1+0+0+0+0+0+0+0+0+1=21 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 = 2

Thus, the function returns 2.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Algorithm Design: Dynamic Programming questions