GATE / CS ARCHIVE

GATE CSE 1997 / QUESTION 15(c)

Count recursive function activations

Algorithms · Asymptotic Analysis & Recurrences · Full GATE CSE 1997 paper

GATE 1997, Q15(c) 1 mark · Descriptive
Report issue

Asymptotic Analysis & Recurrences

Question 15(c), GATE 1997: For positive integers n,m, consider the directly recursive, nonmemoized function
function F(n,m:integer):integer;
begin
  if (n<=0) or (m<=0) then F:=1
  else F:=F(n-1,m)+F(n,m-1)
end.
Use C(s,t)=C(s−1,t)+C(s−1,t−1).
How many calls to F occur when evaluating F(n,m), including the original call?
Question 15(c), GATE 1997: For positive integers n,m, consider the directly recursive, nonmemoized function
function F(n,m:integer):integer;
begin
  if (n<=0) or (m<=0) then F:=1
  else F:=F(n-1,m)+F(n,m-1)
end.
Use C(s,t)=C(s−1,t)+C(s−1,t−1).
How many calls to F occur when evaluating F(n,m), including the original call?
Tap to enlarge
Answer & solution

Answer: 2C(n+m,n)−1. (no official key was published)

The execution forms a full binary recursion tree. Each nonbase call executes exactly two child calls, and each base call has no children. Every base call returns 1, while every internal call returns the sum of its two children's values. The root's return value is consequently the number L of leaf activations. From the recurrence solution, L=F(n,m)=C(n+m,n).

In a full binary tree with I internal nodes and L leaves, the number of edges is 2I because every internal node has two children. It is also I+L−1 because a tree has one fewer edge than nodes. Equating gives I=L−1, so the total number of call activations is I+L=2L−1. Therefore the requested count, including the root call, is

2C(n+m,n)−1.

For n=m=1, the root calls F(0,1) and F(1,0), giving three activations; the formula gives 2·2−1=3. For n=1,m=2 it gives five. If only calls initiated recursively were requested, one would subtract the original root and obtain 2C(n+m,n)−2, but that is not the wording here.

This counts the actual nonmemoized execution tree, including repeated argument pairs as separate calls. Counting only distinct states, or assuming a dynamic-programming implementation, would answer a different complexity question.

Original paper, page 8