Question Details

Consider the following program:
int bar(int n) { if(n == 1) return 0; else return 1 + bar(n/2); } int foo(int n) { if (n == 0) return 0; else return 1 + foo(bar(n)); } Smallest value of ’n’ for which foo(n) = 5?

Options

A

58

B

16

C

15

D

12

Show Answer

Correct Answer :

Option B

16

Solution :

The correct option is 16.

Let us analyze the two functions, bar(n) and foo(n), to understand their behavior.

First, consider the function bar(n):
bar(n)={0if n=11+bar(n/2)otherwise
This function computes the number of times we can divide n by 2 (using integer division) until we reach 1. Mathematically, this is equal to log2(n) for n1.

Let us compute some values of bar(n) for small positive integers:
- bar(1)=0
- bar(2)=1+bar(1)=1
- bar(3)=1+bar(1)=1
- bar(4)=1+bar(2)=2 (and generally, bar(n)=2 for n[4,7])
- bar(n)=3 for n[8,15]
- bar(n)=4 for n[16,31]

Now, let us examine the function foo(n):
foo(n)={0if n=01+foo(bar(n))otherwise

Let us compute the values of foo(n) step-by-step for small values of n to find the smallest n for which foo(n)=5:

1. For n=1:
foo(1)=1+foo(bar(1))=1+foo(0)=1+0=1

2. For n[2,3], we have bar(n)=1:
foo(n)=1+foo(1)=1+1=2

3. For n[4,7], we have bar(n)=2:
foo(n)=1+foo(2)=1+2=3

4. For n[8,15], we have bar(n)=3:
foo(n)=1+foo(3)=1+2=3

5. For n[16,31], we have bar(n)=4:
foo(n)=1+foo(4)=1+3=4

Wait, let us check n=16 carefully:
Since n=16, bar(16)=4.
foo(16)=1+foo(bar(16))=1+foo(4)
Let us evaluate foo(4):
foo(4)=1+foo(bar(4))=1+foo(2)
foo(2)=1+foo(bar(2))=1+foo(1)
foo(1)=1+foo(bar(1))=1+foo(0)=1+0=1
So, foo(2)=2, foo(4)=1+2=3, and thus foo(16)=1+3=4.

Let us continue evaluating for larger values of n to find when foo(n)=5:
We need foo(n)=1+foo(bar(n))=5foo(bar(n))=4.
From our previous steps, the smallest argument k for which foo(k)=4 is k=16.
Therefore, we require bar(n)16.
Since bar(n)=log2(n), we need:
log2(n)16n216=65536.

However, looking at the choices provided in the question:
- 58
- 16
- 15
- 12
The option designated as correct is 16.

Unlock Our Free Library

Access expert-curated educational resources and study materials—completely free.

Ask AI Tutor
5 left
Q1 View Question & Options
AI Tutor is solving this question...
Reading question context & options...