GATE / CS ARCHIVE

GATE CSE 2026 SET 2 / QUESTION 61

Bounding a recursive return value by residues

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

GATE 2026 Set 2, Q61 2 marks · NAT
Report issue

Recursion

Question 61, GATE 2026: The function computes length=end+1−start. It returns 0 if length<1 or start<0 or end<0. Otherwise if length%3==0 it returns func(start+1,end); if length%3==1 it returns 1+func(start,end−1); else it returns func(start+2,end). Find the maximum possible returned value for defined, non-overflowing C executions.
Tap to enlarge
Answer & solution

Official answer: 1

Givens and goal

The function computes length=end+1−start. It returns 0 if length<1 or start<0 or end<0. Otherwise if length%3==0 it returns func(start+1,end); if length%3==1 it returns 1+func(start,end−1); else it returns func(start+2,end). Find the maximum possible returned value for defined, non-overflowing C executions.

Approach

Follow how the interval length moves between residue classes modulo three.

Step-by-step solution

1. For valid endpoints let L=end+1−start>0. The first branch changes L to L−1, the second to L−1 while adding 1, and the third to L−2. Every valid recursive step strictly decreases L, so it eventually reaches a base case.
2. If L≡0 mod 3, the next length is L−1≡2. The following step subtracts 2, reaching L−3≡0. This 0→2→0 cycle never enters residue 1 and therefore contributes no increment.
3. If L≡2 mod 3, its first step goes directly to L−2≡0, followed by the same zero-contribution cycle. If L≡1 mod 3, it adds 1 once and moves to L−1≡0, after which no further increments occur.
4. Invalid endpoints return zero immediately. The value 1 is attainable with start=end=0: length=1, so the function returns 1+func(0,−1)=1+0.
5. Therefore the maximum is 1. This analysis assumes representable arithmetic; evaluating end+1 or changing endpoints beyond signed-int limits can cause undefined behavior and is not a valid counterexample returning a larger defined integer.

Original paper, page 41 · Answer key