ProgrammingVery hardGoldman Sachs OA · TCS Digital
What will be the output of the following pseudocode? (All variables are integers, so / is integer division)
What will be the output of the following pseudocode? (All variables are integers, so / is integer division)
Integer mults = 0
Function pw(Integer x, Integer n)
if (n == 0)
return 1
end if
Integer t = pw(x, n / 2)
t = t * t
mults = mults + 1
if (n mod 2 == 1)
t = t * x
mults = mults + 1
end if
return t
End Function
Print pw(2, 15), mults- A. 32768 14
- B. 16384 8
- C. 32768 7
- D. 32768 8
Correct answer: D. 32768 8
The recursion visits n = 15, 7, 3, 1 (then 0). Each of these 4 levels squares once and, since all are odd, multiplies by x once: 8 multiplications for 2^15 = 32768. Naive repeated multiplication would need 14.
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? String s = "(()(()))()" Integer depth = 0, best = 0, pairs = 0 for (each i from 0 to…
- What will be the output of the following pseudocode? (^ is XOR, & is AND) Integer s = 0, x, p for (each i from 1 to 20) x = i p = 0 while…
- What will be the output of the following pseudocode? Integer P[4][4] = all 0 Integer A[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} for (each…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Function f(Integer n) if (n <…
- What will be the output of the following pseudocode? // BST: smaller keys go to the left, larger to the right Insert into an empty BST, in…
- What will be the output of the following pseudocode? Function ways(Integer n) if (n < 0) return 0 end if if (n == 0) return 1 end if…