ProgrammingVery hardProduct company OA
How many TOTAL calls to fib (including the initial call) are made evaluating fib(4), given this naive recursive implementation?
How many TOTAL calls to `fib` (including the initial call) are made evaluating `fib(4)`, given this naive recursive implementation?
int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}- A. 4
- B. 7
- C. 5
- D. 9
Correct answer: D. 9
Expanding the call tree: fib(4) calls fib(3)+fib(2); fib(3) calls fib(2)+fib(1); each fib(2) calls fib(1)+fib(0). Counting every invocation (fib(4), fib(3), fib(2)x2, fib(1)x3, fib(0)x2) totals 9 calls.
More C Programming questions
- What is printed? (recursion where the recursive call's result is deliberately ignored) c int calls = 0; int f(int n) { calls++; if (n <=…
- What is printed? (recursion depth vs. the array being modified on the way back up) c int a[5] = {1, 2, 3, 4, 5}; void f(int i) { if (i >=…
- What is printed? (recursion with an early return skipping the rest of the function) c int f(int n) { if (n < 0) return -1; if (n == 0)…
- What is printed? (binary string of n using recursion, division by 2) c void toBinary(int n) { if (n == 0) return; toBinary(n / 2)…
- What is printed? (two mutually exclusive recursive branches selected by a condition, with accumulation via return value) c int f(int n) {…
- What is printed? (recursion where the base case is reached via an off-by-one condition) c int f(int n) { if (n < 1) return 0; return n +…