GATE / CS ARCHIVE

GATE CSE 2018 / QUESTION 21

Counting recursive calls

Programming in C · Recursion · Full GATE CSE 2018 paper

GATE 2018, Q21 1 mark · NAT
Report issue

Recursion

Question 21, GATE 2018: Global int counter starts at 0. calc(a,b) increments counter, returns a*a*a if b==3, otherwise sets c=calc(a,b/3) and returns c*c*c. main calls calc(4,81), discards its return, then prints counter. Find the intended output.
Tap to enlarge
Answer & solution

Official answer: 4

Our answer: 4 in intended call-count model; signed-overflow caveat

Method

Count activations on the descent separately from arithmetic on the return path. Calls occur at b=81,27,9,3; the last still increments counter before testing the base case. Unwinding produces mathematical values 4³,4⁹,4²⁷,4⁸¹. Already 4²⁷=2^54 exceeds a signed 32-bit range, and the final 2^162 exceeds signed 64-bit range. Thus counting gives the intended answer, but actual C execution is not guaranteed once signed overflow occurs.

Solution

The b arguments are 81, 27, 9, 3, so counter is incremented four times before the base return. The intended answer is 4. However the return computation then cubes repeatedly to 4^81=2^162, overflowing signed int on ordinary 32-bit or 64-bit implementations. Signed overflow is undefined behavior in C even if main discards the return value, so the printed result is not portable without sufficiently wide integer arithmetic or an explicit abstraction that ignores overflow.

Original paper, page 9 · Answer key