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.

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
collegedunia
Verified By Collegedunia

Correct Answer: 65536

Solution and Explanation

Step 1: Analyze bar(n)

The function bar(n) repeatedly performs integer division \(n \to n/2\) until n becomes 1, counting the number of divisions performed. So bar(n) simply counts how many times n can be halved before reaching 1, which equals \(\lfloor \log_2 n \rfloor\). This means bar(n) = m for every n satisfying \(2^m \le n \le 2^{m+1}-1\), and the smallest such n is \(2^m\).

Step 2: Analyze foo(n)

We have foo(1) = 1, and for n > 1, foo(n) = 1 + foo(bar(n)). So foo(n) equals 1 plus however many more steps foo needs starting from bar(n).

Step 3: Set up a recurrence for the smallest n

Let \(n_k\) be the smallest positive integer with foo(n_k) = k. Clearly \(n_1 = 1\). For k > 1, foo(n_k) = k requires foo(bar(n_k)) = k-1, so bar(n_k) must equal \(n_{k-1}\), the smallest number giving foo value k-1. Since the smallest n with bar(n) = m is \(2^m\), we get: \[n_k = 2^{n_{k-1}}, \quad n_1 = 1.\]

Step 4: Build the tower up to k = 5

\[n_1 = 1\] \[n_2 = 2^{1} = 2\] \[n_3 = 2^{2} = 4\] \[n_4 = 2^{4} = 16\] \[n_5 = 2^{16} = 65536\]

Step 5: Verify by direct substitution

bar(65536) = 16 since \(2^{16} = 65536\), so foo(65536) = 1 + foo(16). Next bar(16) = 4, so foo(16) = 1 + foo(4). Then bar(4) = 2, so foo(4) = 1 + foo(2). Finally bar(2) = 1, so foo(2) = 1 + foo(1) = 1 + 1 = 2. Working back up: foo(4) = 3, foo(16) = 4, foo(65536) = 5, exactly as required.

The smallest positive integer n for which foo(n) returns 5 is:

\[\boxed{n = 65536}\]
Was this answer helpful?
0
0

Top GATE CS Computer Science and IT Engineering Questions

View More Questions

Top GATE CS Programming and Data Structures Questions

View More Questions