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 returns is . (answer in integer)
Note: Ignore syntax errors (if any) in the function.
View worked solution
Answer: 65536 : 65536
To find the smallest positive integer for which , let us analyze the behavior of both recursive functions.
1. Behavior of bar(n):
- For ,
This recurrence computes the floor of the base-2 logarithm: .
2. Behavior of foo(n):
- For ,
3. Working Backwards to Minimize :
Let be the smallest positive integer such that .
- For : The smallest value is .
- For : We need . To minimize , we need the smallest .
smallest . - For : We need . To minimize , we need the smallest .
smallest . - For : We need . To minimize , we need the smallest .
smallest . - For : We need . To minimize , we need the smallest .
smallest .
Thus, the smallest positive integer for which returns is .
Free practice · Your answers on this page are not saved.
