ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int calls;
int f(int n) { calls++; return n < 3 ? n : f(n - 1) + f(n - 3); }
int main(void) {
    int r = f(8);
    printf("%d %d", r, calls);
}
  1. A. 15 25
  2. B. 15 17
  3. C. 21 67
  4. D. 13 25

Correct answer: A. 15 25

Values: f(0..2) = 0, 1, 2, then f(n) = f(n − 1) + f(n − 3): 2, 3, 5, 7, 10, 15. Calls obey C(n) = 1 + C(n − 1) + C(n − 3) with C(0..2) = 1: 3, 5, 7, 11, 17, 25. Both operands update the same global, but each update happens inside a function call, and function calls are not interleaved, so the total is well defined whichever operand runs first. '21 67' uses the Fibonacci recurrence f(n − 2).

More C Programming questions

Exams that ask this topic