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);
}
  1. A. 13 19
  2. B. 8 25
  3. C. 10 15
  4. 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

Exams that ask this topic