GATE CS 2016, set 2 · Question 45 · Programming and Data Structures · Multiple choice (MCQ) · 2 marks · −2/3 for a wrong answer

The following function computes X^Y for positive integers X and Y.
int exp(int X, int Y) { int res = 1, a = X, b = Y; while ( b != 0 ){ if ( b%2 == 0) { a = a*a; b = b/2; } else { res = res*a; b = b-1; } } return res; }
Which one of the following conditions is TRUE before every iteration of the loop?

  1. (A) X^Y = aᵇ
  2. (B) (res * a)^Y = (res * X)ᵇ
  3. (C) X^Y = res * aᵇ
  4. (D) X^Y = (res * a)ᵇ
Answer

Answer (C)

Answer from the official GATE CS 2016 answer key.

The step-by-step solution, where available, is part of GATE CS Pro. See what Pro includes