ProgrammingModerateTCS NQT · Infosys SP

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer p[4] = {2, 0, 3, 1}       // coefficients of 2x³ + 0x² + 3x + 1
Integer x = 3, m = 7, r = 0
for (each i from 0 to 3)
    r = (r * x + p[i]) mod m
end for
Print r
  1. A. 1
  2. B. 64
  3. C. 0
  4. D. 6

Correct answer: A. 1

Horner's rule evaluates 2x³ + 3x + 1 at x = 3 modulo 7: 54 + 9 + 1 = 64 = 9 × 7 + 1, so r = 1. Reducing at every step gives the same remainder as reducing at the end.

More Pseudocode and Code Tracing questions

Exams that ask this topic