GATE / CS ARCHIVE

GATE CSE 2015 SET 2 / QUESTION 24

GATE CSE 2015 Set 2 Q24

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

GATE 2015 Set 2, Q24 1 mark · NAT
Report issue

Recursion

Question 24, GATE 2015: int fun(int n){int x=1, k; if(n==1)return x; for(k=1; k<n; ++k)x=x+fun(k)*fun(n-k); return x; } Find fun(5).
Tap to enlarge
Answer & solution

Official answer: 51

Step through it (34 steps)

Let F1=1 and Fn=1+sum(Fk F(n−k), k=1..n−1). Then F2=2, F3=5, F4=15, F5=1+15+10+10+15=51. Values fit int in this call.

The function’s accumulator begins at 1 on every call. Its recurrence is F(n)=1+Σ F(k)F(n−k), with F(1)=1. Compute bottom-up: F(2)=1+1=2; F(3)=1+2+2=5; F(4)=1+5+4+5=15. For n=5, the four products are 15, 10, 10, 15, and the initial 1 makes 51. Forgetting the initial 1 would incorrectly substitute a different recurrence.

Original paper, page 34 · Answer key