ProgrammingHardTCS NQT · Accenture pattern
Consider this naive recursive Fibonacci. How many TOTAL calls to fib (including the initial call) happen when computing fib(5)?
Consider this naive recursive Fibonacci. How many TOTAL calls to fib (including the initial call) happen when computing fib(5)?
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(5)- A. 9
- B. 13
- C. 15
- D. 17
Correct answer: C. 15
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(5) (value 5) gives 15 total calls — it is NOT simply 2×5-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 = 62 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? (All variables are integers, so / is integer division.) Function f(Integer n, Integer…
- What will be the output of the following pseudocode? (& is bitwise AND, >> is right shift.) Integer n = 3500, c = 0 while (n > 0) c = c +…
- What is the final content of the queue (front to back, left to right) after this sequence of operations on an initially empty queue?…