ProgrammingHardCapgemini · Infosys pattern
What will be the output of the following pseudocode (fast exponentiation)? (All variables are integers, so / is integer division.)
What will be the output of the following pseudocode (fast exponentiation)? (All variables are integers, so / is integer division.)
Integer calls = 0
Function fp(Integer a, Integer b)
calls = calls + 1
if (b == 0)
return 1
end if
Integer h = fp(a, b / 2)
if (b mod 2 == 0)
return h * h
end if
return a * h * h
End Function
Print fp(3, 7), calls- A. 2187 3
- B. 2187 4
- C. 3 4
- D. 2187 7
Correct answer: B. 2187 4
3^7 = 2187. b halves at each level: 7->3->1->0, which is exactly 4 recursive calls (including the base case), matching the exponential-by-squaring pattern.
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 (checking if one string is a rotation of another)? Function isRotation(String a…
- What will be the output of the following pseudocode (counting total set bits across 1..n)? Function countSetBitsRange(Integer n) Integer…
- What will be the output of the following pseudocode (depth-first traversal of a graph given as an adjacency list)? Map graph = {0: [1, 2]…
- What will be the output of the following pseudocode (breadth-first traversal using a queue)? Map graph = {0: [1, 2], 1: [0, 3], 2: [0, 3]…
- What will be the output of the following pseudocode? Integer x = 1, i = 1 while (i <= 5) x = x + i i i = i + 1 end while Print x
- What will be the output of the following pseudocode? Integer c = 0, n = 5 for (each i from n down to 1) for (each j from 1 to i) if (j mod…