ProgrammingVery hardProduct company OA · code-tracing level
What will be the output of the following pseudocode? (memo starts with every entry equal to −1; calls counts every call, including the first.)
What will be the output of the following pseudocode? (memo starts with every entry equal to −1; calls counts every call, including the first.)
Integer memo[0..20] = all -1, calls = 0
Function f(Integer n)
calls = calls + 1
if (n <= 1)
return n
end if
if (memo[n] != -1)
return memo[n]
end if
memo[n] = f(n - 1) + f(n - 2)
return memo[n]
End Function
Print f(15), calls- A. 610 29
- B. 610 1973
- C. 610 15
- D. 987 29
Correct answer: A. 610 29
f(15) is the 15th Fibonacci number, 610. Because f(n − 1) is evaluated first, the calls go straight down the chain f(15), f(14), …, f(2), each doing real work exactly once (14 calls). Each of these makes 2 calls; by the time f(n − 2) is called it is either memoised or a base case and returns immediately. Total calls = 1 + 2 × 14 = 29. 1973 = 2 × 987 − 1 is the call count without memoisation; 15 forgets the memo-hit calls, which still count.
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? (calls counts every call, including the first.) Integer calls = 0 Function g(Integer…
- What will be the output of the following pseudocode? (& is bitwise AND and >> is a right shift.) Integer c = 0 for (each x from 1 to 200)…
- What will be the output of the following pseudocode? (Integers are in two's complement, so −i flips the bits of i and adds 1; & is bitwise…
- What will be the output of the following pseudocode? (& is bitwise AND.) Integer c = 0, x for (each i from 0 to 63) x = i while (x > 0) x…
- What will be the output of the following pseudocode? Integer n = 30, c = 0, j for (each i from 1 to n) j = i while (j <= n) c = c + 1 j =…
- What will be the output of the following pseudocode? Integer c = 0 for (i = 1; i <= 100; i = i 2) for (j = i; j <= 100; j = j + 1) c = c +…