Question
The following function computes for positive integers and .
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?
Official answer and solution
- Official answer
- C
- From
- Official GATE 2016 answer key
Solution
Identify the loop invariant of the binary exponentiation algorithm.
The function implements the classic binary exponentiation algorithm (exponentiation by squaring) to compute .
Trace the loop variables:
- Initial state:
res = 1,a = X,b = Y.
Testing Option (C): . The relation holds initially.
Inductive step: Assume holds before an iteration with :
- Case 1: is even ().
The code updates and , leavingresunchanged. - Case 2: is odd ().
The code updates and , leavingaunchanged.
In both branches, the quantity is invariant and remains equal to .
When the loop terminates ():
Therefore, the condition is TRUE before every iteration of the loop (Option C).
C
Selecting , which only holds at initialization and is violated as soon as res is multiplied.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2016 Computer Science and Information Technology (CS) Session 2
- Question
- 45 of 65, printed as CS Q.35
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.