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);
}- A. 31
- B. 59
- C. 2692537
- 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
- What is printed? c #include <stdio.h> int main(void) { int arr[2 3 + 1]; printf("%zu", sizeof arr / sizeof arr[0]); }
- How many paths go from the top-left to the bottom-right of a 3 by 3 grid of points, moving right or down, without passing through the…
- What is printed? c #include <stdio.h> int main(void) { int a = 2147483647; printf("%u", (unsigned)a + 1u); }
- How many integers from 1 to 64 have their low three bits all clear? Compute with this program. c #include <stdio.h> int main(void) { int c…
- How many times does the letter g occur in "programming"? The program counts it with a pointer walk. c #include <stdio.h> int main(void) {…
- What is printed? c #include <stdio.h> int main(void) { int x = 10; printf("%d %d", x & -x, x & (x - 1)); }