=========================================================================== CSC 236 Sample Solutions for Week 8 Tutorial Fall 2007 =========================================================================== Prove that the following algorithm is correct, with respect to the conditions given. Precondition: x in R, y in N Postcondition: pow(x,y) returns x^y (with convention 0^0 = 1) pow(x, y): if y == 0: return 1 elif y % 2 == 0: t = pow(x, y/2) return t * t else: t = pow(x, (y-1)/2) return t * t * x Q: How do we measure input size? A: Input size = y (just like last week's recurrence). Q: What are we proving exactly, and how? A: For all y in N, for all x in R, pow(x,y) returns x^y, by induction on y. Q: What's first? A: Base Case: y = 0 Q: Proof? A: For all x in R, pow(x,y) = pow(x,0) returns 1 = x^0 = x^y. Q: What's next? A: Ind. Hyp.: Q: Statement? A: Let y > 0 and suppose pow(x,j) returns x^j for 0 <= j < y. Q: What's next? A: Ind. Step: Let x in R and consider call pow(x,y). Q: Approach? A: Following algorithm, consider cases y even and y odd. Case 1: y even (i.e., y % 2 = 0) Q: What's next? A: Ensure recursive call meets precondition and size is within range of I.H.: y even and y > 0 implies 0 <= y/2 < y Q: And now? A: Apply IH: so by IH, pow(x, y/2) returns x^{y/2} Conclude: and current call returns x^{y/2} * x^{y/2} = x^{y/2+y/2} = x^y. Case 2: y odd (i.e., y % 2 = 1) Q: What's next? A: Ensure recursive call meets precondition and size is within range of I.H.: y odd and y > 0 implies 0 <= (y-1)/2 < y Q: And now? A: Apply IH: so by IH, pow(x, (y-1)/2) returns x^{(y-1)/2} Conclude: and current call returns x^{(y-1)/2} * x^{(y-1)/2} * x = x^{(y-1)/2+(y-1)/2+1} = x^{y-1+1} = x^y. In all cases, current call returns x^y, i.e., for all x in R, pow(x,y) returns x^y. By induction, for all y in N, for all x in R, pow(x,y) returns x^y.