ProgrammingHardProduct company OA
What is printed?
What is printed?
int calls = 0;
int f(int n) {
calls++;
return n < 2 ? n : f(n / 2) + f(n - 1);
}
int main(void) {
int r = f(6);
printf("%d %d", r, calls);
}- A. 13 19
- B. 8 25
- C. 10 15
- D. 10 19
Correct answer: D. 10 19
Build up: f(0)=0, f(1)=1, f(2)=f(1)+f(1)=2, f(3)=f(1)+f(2)=3, f(4)=f(2)+f(3)=5, f(5)=f(2)+f(4)=7, f(6)=f(3)+f(5)=10. Calls obey C(n) = 1 + C(n/2) + C(n−1) with C(0)=C(1)=1, giving 3, 5, 9, 13, 19. '8 25' is the Fibonacci answer for the wrong recurrence.
More C Programming questions
- Assume 32-bit unsigned int. What is printed? c unsigned x = 0xB8; / 1011 1000 / printf("%u %u %u", x & (x - 1), x | (x - 1), x & -x);
- What is printed? c int f(void) { static int n = 5; return n--; } int main(void) { int s = 0; while (f() > 2) s++; printf("%d %d", s, f()); }
- What is printed? c #define MUL(a, b) a b #define ADD(a, b) a + b printf("%d", MUL(ADD(1, 2), ADD(3, 4)));
- Assume little-endian, 8-bit char and 32-bit unsigned int. What is printed? c union { unsigned int u; unsigned char b[4]; } x; x.u =…
- What is printed? c int a = 6, b = 2; int r = a & 3 << b | 1; printf("%d", r);
- What is printed? c int i = 1, j = 2, k = 3; int r = (i > j) ? i++ : j > k ? j++ : (k++, i + j + k); printf("%d %d %d %d", i, j, k, r);