GATE Computer ScienceHardGATE CS (PYQ pattern)

long p(long x, int n) { if (n == 0) return 1; if (n % 2 == 0) { long h = p(x, n / 2); return h * h; } return x * p(x, n - 1); } How many multiplications (every * executed, in all calls) does p(3, 45) perform?

  1. A. 9
  2. B. 7
  3. C. 12
  4. D. 10

Correct answer: A. 9

45 is odd (x*), 44 even (square), 22 even, 11 odd, 10 even, 5 odd, 4 even, 2 even, 1 odd, 0: counting the multiplication in every level gives 9.

More Programming and Data Structures (GATE) questions

Exams that ask this topic