Skip to main content

GATE CSE 2026Algorithms › Recursion & Recurrence RelationsVerified

GATE CSE 2026 PYQ: Consider the recursive functions represented by the following code segment: int bar ( int n ) { if ( n == 1…

Consider the recursive functions represented by the following code segment:

  1. int bar(int n) {
  2. if (n == 1) return 0;
  3. else return 1 + bar(n/2);
  4. }
  5. int foo(int n) {
  6. if (n == 1) return 1;
  7. else return 1 + foo(bar(n));
  8. }

The smallest positive integer n for which f∘∘(n)\mathrm{f} \circ \circ(\mathrm{n}) returns 5 is ____\_\_\_\_. (answer in integer)

Note: Ignore syntax errors (if any) in the function.

    Answer

    65536

    Approach

    Interpret $\texttt{bar(n)} \text{as the number of divisions by} 2 \text{needed to reduce} n \text{to} 1, i.e.$ $\lfloor\log_2 n\rfloor$. Then $\texttt{foo(n)}$ satisfies $\texttt{foo}(1)=1$ and $\texttt{foo}(n)=1+\texttt{foo}(\texttt{bar}(n))$. To get $\texttt{foo}(n)=5$, we need the smallest n whose $\texttt{bar} \text{value is the smallest input that makes} \texttt{foo} \text{return} 4,$ and so on backwards through the recurrences.

    The value of $\texttt{bar(n)}$ is $\lfloor\log_2 n\rfloor$. To make $\texttt{foo(n)} \text{return} 5, \text{the argument passed to the nested} \texttt{foo} \text{call must be the smallest integer returning} 4, \text{which is} 16. \text{The smallest} n$ for which $\texttt{bar}(n)=16$ is $2^{16}=65536$. Thus the required smallest positive integer is 65536.

    Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.