GATE / CS ARCHIVE

GATE CSE 2021 SET 2 / QUESTION 49

GATE CSE 2021 Set 2 Q49

Programming in C · Recursion · Full GATE CSE 2021 Set 2 paper

GATE 2021 Set 2, Q49 2 marks · NAT
Report issue

Recursion

Question 49, GATE 2021: foo(x,y,q): if x≤0 and y≤0 return q; if x≤0 return foo(x,y−q,q); if y≤0 return foo(x−q,y,q); otherwise return foo(x,y−q,q)+foo(x−q,y,q). What does printing foo(15,15,10) yield?
Tap to enlarge
Answer & solution

Official answer: 60

Step through it (33 steps)

With q=10, each initial coordinate 15 requires two decrements to become nonpositive. When both remain positive the recursion branches on which coordinate decreases; once one is nonpositive only the other can decrease. Thus leaves correspond to the six interleavings of two x decrements and two y decrements, binomial(4, 2)=6. Each leaf returns 10, so the output is 60. There are no side effects across recursive calls, so unspecified operand evaluation order does not affect this sum.

Let F(i,j) denote the return with i,j remaining decrements needed. Interior recurrence F(i,j)=F(i−1,j)+F(i,j−1), with F(i,0)=F(0,j)=10. Hence F(1,1)=20, F(1,2)=F(2,1)=30, F(2,2)=60. The base is reached at −5, not necessarily exactly zero, because tests are nonpositive.

Original paper, page 85 · Answer key