Question:hard

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.

Show Hint

Notice bar(n) = floor(log2(n)), so foo(n) counts how many times log2 must be applied before reaching 1. Build the smallest n from the bottom up: start at 1, then repeatedly raise 2 to the previous value: 1, 2, 2^2=4, 2^4=16, 2^16=65536, which is the smallest n giving foo(n)=5.
Updated On: Aug 3, 2026
Show Solution

Correct Answer: 65536

Solution and Explanation

Think of foo(n) as counting how many times a bar-reduction must be applied before the value collapses to 1, where each bar-step itself needs a large enough input to fire correctly.

Setting up bar(n): bar(n) repeatedly floors n/2 until it hits 1, counting the steps, so bar(n) = \(\lfloor \log_2 n \rfloor\). To force bar(n) = t using the smallest possible n, pick \(n = 2^t\), the left edge of the range \([2^t, 2^{t+1}-1]\) that all give the same bar value t.

Unrolling foo(n): Since foo(1) = 1 and foo(n) = 1 + foo(bar(n)) otherwise, requiring foo(n) = 5 peels off one bar layer at a time:

foo(n) = 5 needs foo(bar(n)) = 4, which needs foo(bar(bar(n))) = 3, which needs foo(bar(bar(bar(n)))) = 2, which needs foo(bar(bar(bar(bar(n))))) = 1.

The innermost condition foo(x) = 1 holds only at \(x = 1\). To reach that minimal value from the previous stage using the smallest possible source, the source number must be \(2^{x}\) (since that is the smallest n giving bar(n) = x). Applying this doubling-in-the-exponent step four times starting from \(x = 1\):

\(x_0 = 1\) needs foo value 1

\(x_1 = 2^{x_0} = 2\) gives foo value 2

\(x_2 = 2^{x_1} = 4\) gives foo value 3

\(x_3 = 2^{x_2} = 16\) gives foo value 4

\(x_4 = 2^{x_3} = 2^{16} = 65536\) gives foo value 5

Since at each stage the smallest valid source number was chosen, this exponent tower \(2^{2^{2^{2}}} = 2^{16} = 65536\) is guaranteed to be the least n satisfying the condition.

Final answer: \(n = 65536\)

Was this answer helpful?
0


Questions Asked in GATE CS exam