StreakPeaked· Practice

ExamsGATETechnical

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^b
  2. (B) (res*a)^Y = (res*X)^b
  3. (C) X^Y = res * a^b
  4. (D) X¹ = (res * a)^b

Correct answer: (C) X^Y = res * a^b

Solution

The condition X^Y = res * a^b holds true before each iteration because the algorithm progressively breaks down the exponent Y while maintaining the product of the accumulated result (res) and the current base (a) raised to the remaining exponent (b). This ensures that the overall value of X^Y is preserved throughout the loop.

Related GATE Technical questions

⚔️ Practice GATE Technical free + battle 1v1 →