ProgrammingVery hardProduct company OA · GATE CS

What is printed?

What is printed?
long memo[50];
int calls = 0;
long f(int n) {
    calls++;
    if (n < 2) return n;
    if (memo[n]) return memo[n];
    return memo[n] = f(n - 1) + f(n - 2);
}
int main(void) {
    long r = f(10);
    printf("%ld %d", r, calls);
}
  1. A. 55 19
  2. B. 55 177
  3. C. 55 11
  4. D. 89 19

Correct answer: A. 55 19

The first descent f(10) → f(9) → … → f(1) makes 10 calls. On the way back each f(n − 2) is either a cached hit or a base case: 9 more calls, 19 in all. Without the memo it would take 177 calls. f(10) = 55.

More C Programming questions

Exams that ask this topic