ProgrammingVery hardProduct company OA
What will be the output of the following pseudocode? (calls counts every call, including the first; memo starts with every entry equal to −1.)
What will be the output of the following pseudocode? (calls counts every call, including the first; memo starts with every entry equal to −1.)
Integer calls = 0, memo[0..20]
Function f(Integer n)
calls = calls + 1
if (n < 3)
return 1
end if
if (memo[n] != -1)
return memo[n]
end if
memo[n] = f(n - 1) + f(n - 3)
return memo[n]
End Function
Print f(10), calls- A. 28 15
- B. 28 17
- C. 19 17
- D. 28 9
Correct answer: B. 28 17
Values: f(0..2) = 1, f(3) = 2, f(4) = 3, f(5) = 4, f(6) = 6, f(7) = 9, f(8) = 13, f(9) = 19, f(10) = 19 + 9 = 28. Calls: the chain f(10), f(9), …, f(3), f(2) is 9 calls; each of the 8 computed values f(10)…f(3) also makes one f(n − 3) call (f(7) … f(0)), which is answered by the memo or the base case: 9 + 8 = 17. Forgetting that memo hits still count as calls gives a smaller number; 19 is f(9).
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? (/ is integer division.) Integer c = 0 for (n = 1 to 50) Integer d = 0 for (k = 1 to…
- What will be the output of the following pseudocode? (&, |, ^ are bitwise AND, OR, XOR; << is a left shift.) Integer x = 0 for (i = 0 to…
- What will be the output of the following pseudocode? ('ref' parameters are passed by reference; others by value.) Procedure p(ref Integer…
- What will be the output of the following pseudocode? (/ is integer division.) Function A(Integer n) if (n <= 1) return n end if return B(n…
- What will be the output of the following pseudocode? (x is an 8-bit unsigned value; & is bitwise AND, | is OR, << and >> are shifts.)…
- What will be the output of the following pseudocode? (/ is integer division.) Integer x = 10 x = x + x 2 - 4 / 2 Print x