Question

Consider the recursive functions represented by the following code segment:

int bar(int n){
     if (n == 1) return 0;
     else return 1 + bar(n/2);
}

int foo(int n){
     if (n == 1) return 1;
     else return 1 + foo(bar(n));
}

The smallest positive integer n for which foo(n) returns 5 is ______. (answer in integer)

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

Official answer and solution
Official answer
65536
From
Official GATE 2026 answer key

Solution

Observe that bar(n) computes ⌊log⁡2n⌋\lfloor \log_2 n \rfloor, and work backwards from foo(1) = 1 to foo(n) = 5 by choosing the smallest nn at each step.

  1. The function bar(n) counts how many times n is divided by 2 until it reaches 1, so bar(n)=⌊log⁡2n⌋\text{bar}(n) = \lfloor \log_2 n \rfloor for all n≥1n \ge 1. Notice that the smallest positive integer nn for which bar(n)=k\text{bar}(n) = k is n=2kn = 2^k.
  2. Working backwards for foo(n):
    • foo(n)=1  ⟹  n=1\text{foo}(n) = 1 \implies n = 1
    • foo(n)=2  ⟹  foo(bar(n))=1  ⟹  bar(n)=1  ⟹  nmin⁡=21=2\text{foo}(n) = 2 \implies \text{foo}(\text{bar}(n)) = 1 \implies \text{bar}(n) = 1 \implies n_{\min} = 2^1 = 2
    • foo(n)=3  ⟹  bar(n)=2  ⟹  nmin⁡=22=4\text{foo}(n) = 3 \implies \text{bar}(n) = 2 \implies n_{\min} = 2^2 = 4
    • foo(n)=4  ⟹  bar(n)=4  ⟹  nmin⁡=24=16\text{foo}(n) = 4 \implies \text{bar}(n) = 4 \implies n_{\min} = 2^4 = 16
    • foo(n)=5  ⟹  bar(n)=16  ⟹  nmin⁡=216=65536\text{foo}(n) = 5 \implies \text{bar}(n) = 16 \implies n_{\min} = 2^{16} = 65536.
Final answer

65536

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2026 Computer Science and Information Technology - Session 1 (CS1)
Question
61 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.