ProgrammingVery hardTCS NQT · Accenture pattern
Consider this naive recursive Fibonacci. How many TOTAL calls to fib (including the initial call) happen when computing fib(6)?
Consider this naive recursive Fibonacci. How many TOTAL calls to fib (including the initial call) happen when computing fib(6)?
Function fib(Integer k)
[call count += 1 happens here]
if (k <= 1)
return k
end if
return fib(k - 1) + fib(k - 2)
end Function
fib(6)- A. 11
- B. 23
- C. 25
- D. 27
Correct answer: C. 25
Each call to fib(k) with k > 1 spawns exactly two further calls, fib(k-1) and fib(k-2), down to the base cases. Counting every call in the full recursion tree for fib(6) (value 8) gives 25 total calls — it is NOT simply 2×6-1.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (Arrays are passed and assigned BY REFERENCE: b = a makes b point to the same array…
- What will be the output of the following pseudocode? (^ is bitwise XOR.) Integer x = 90, y = 76 x = x ^ y y = x ^ y x = x ^ y Print x, y
- What will be the output of the following pseudocode? (A square matrix's main diagonal is mat[i][i]; its anti-diagonal is mat[i][n-1-i]. If…
- What will be the output of the following pseudocode? (A square matrix's main diagonal is mat[i][i]; its anti-diagonal is mat[i][n-1-i]. If…
- This function uses a counter that PERSISTS across calls (a static/global variable), starting at 3. What does each of the 6 calls print, in…
- What will be the output of the following pseudocode? Function isEven(Integer n) if (n == 0) return true end if return isOdd(n - 1) end…