GATE DA 2025 | Question 63

NAT · 2 marks

Consider the following Python code snippet.

def f(a,b):
    if (a==0):
        return b
    if (a%2==1):
        return 2*f((a-1)/2,b)
    return b+f(a-1,b)
print(f(15,10))

The value printed by the code snippet is ________ (Answer in integer)

Answer

160

Explanation

From \(a = 15\), every value of \(a\) reached is odd until 0, so only return 2*f((a-1)/2,b) runs:

\[ f(15, 10) = 2f(7, 10) = 4f(3, 10) = 8f(1, 10) = 16f(0, 10) = 16 \times 10 = 160 \]

In Python 3, (a-1)/2 gives floats (7.0, 3.0, 1.0, 0.0), but the tests a%2==1 and a==0 behave just as they would for integers, and the result stays an integer because it is built from b = 10.

In general the function returns \((a + 1) \cdot b\), not \(a \cdot b\), so 150 is the tempting wrong answer.

Answer: 160