ProgrammingVery hardCompetitive coding (CP)

What is printed by this memoised recursion? The static memo table starts with every entry zero, and calls counts each call to f.

What is printed by this memoised recursion? The static memo table starts with every entry zero, and calls counts each call to f.
#include <stdio.h>
int calls = 0;
long long f(int n) {
    static long long memo[31];
    calls++;
    if (n < 2) return n;
    if (memo[n]) return memo[n];
    memo[n] = f(n - 1) + f(n - 2);
    return memo[n];
}
int main(void) {
    f(30);
    printf("%d", calls);
}
  1. A. 31
  2. B. 59
  3. C. 2692537
  4. D. 29

Correct answer: B. 59

The chain f(30), f(29), ..., f(1) makes 30 calls, and each f(n) for n = 2..30 also makes one cheap call f(n - 2), adding 29: 59. 29 counts only cache misses, 31 assumes one call per value 0..30, and 2692537 is the call count without memoisation.

More C Programming questions

Exams that ask this topic