GATE / CS ARCHIVE

GATE CSE 1994 / QUESTION 21

Maximum recursion depth in Fibonacci

Programming in C · Recursion · Full GATE CSE 1994 paper

GATE 1994, Q21 5 marks · Descriptive
Report issue

Recursion

Question 21, GATE 1994: fib(n)=1 for n=0 or 1; otherwise fib(n)=fib(n−1)+fib(n−2). The available stack is 64 bytes. Each activation stores only a 2-byte return address and a 2-byte integer parameter. Estimate the largest nonnegative n without overflow. GateForum prints parameter “1” in the header but uses n in the body; GFG uses n.
Tap to enlarge
Answer & solution

Answer: n=16 under the stipulated 4-byte-per-activation model, counting the initial fib call. (no official key was published)

Each active invocation occupies 2+2=4 bytes, so the stack can hold 64/4=16 simultaneously active invocations. The relevant quantity is peak recursion depth, not the exponentially growing total number of calls: completed calls return and free their space before their siblings finish.

Let D(n) be the largest number of simultaneously active fib frames, including the current frame. D(0)=D(1)=1, and for n≥2, D(n)=1+max(D(n−1),D(n−2)). It follows that D(n)=n for n≥1. For example fib(3)→fib(2)→fib(1) contains three active frames; the longest chain from fib(n) descends through n−1,n−2,…,1. The alternative final call at zero has no extra level, because fib(1) is a base case and does not call fib(0).

Therefore n=16 uses exactly 64 bytes, while n=17 needs 68 bytes. Both base cases need just four bytes. This estimate assumes the full 64 bytes are available to fib, its initial activation is stack-resident, and intermediate results, frame links, saved registers and runtime bookkeeping incur no further stack charge, exactly as stipulated. A real implementation may need more storage. Excluding the initial activation would shift the numerical bound to 17, but that is a different accounting convention, not the model used here.

Original paper, page 6