Directions: Use your own paper for answers. When you are done you may keep this exam sheet. The answers will be posted.
int exp(int X, int Y) { int x = X, y = Y, z = 1; while (y > 0) { while (y%2 == 0) { x = x*x; y = y/2; } z = z*x; y = y - 1; } return z; }Suppose one knows that the following equation is true, for integer variables x, y, z, X, and Y, and = is the mathematical equals:
z * xy = XYand suppose the following 2 assignment statements are executed, where = is assignment:
z = z * x; y = y - 1;a. Prove that the equation remains true (remains invariant) after the two assignments are executed.
b. At the point in the above algorithm just before the two assignments statements, it is also true that y%2 is not zero, that is, y is odd. Is this needed for the proof of invariance?
In light of the above two parts, consider the following C, C++, or Java function?
int exp(int X, int Y) { int x = X, y = Y, z = 1; while (y > 0) { z = z*x; y = y - 1; } return z; }c. Do you think this second function will correctly calculate XY ?
d. Do you think this version of exp is of any use?