|
CS 3343/3341 Analysis of Algorithms Spring 2012 Recitation 8 Exam Review Partial Answers |
Consider the following function that will calculate the quotient and remainder of its two input parameters. (It does with this without using an actual "divide", but just with addition and subtraction.) The inputs are: n >= 0 (the "dividend") and d >= 1 (the "divisor"). The algorithm calculates and returns: q >= 0 (the "quotient") and d >= 1 (the "divisor"). r (the "remainder"), such that on termination, the following are true: r >= 0, r < d, and n = d * q + r. | Here is the picture:q +------- d | n -----+ ------- rHere is the function: // div: inputs n >= 0 and d >= 1 // returns the pair (q, r) (int, int) div(int n, int d) { int q = 0, r = n; while (r >= d) { q = q + 1; r = r - d; } return (q, r); }The loop invariant is: n = d * q + r Carefully write out all four steps in the proof. |
satisfying the conditions in red above, this is the very definition of division. |
i | r | Action | A={6,7,8,9} |
---|---|---|---|
0 | 2 | Inter(0,2) | A={8,7,6,9} |
1 | 1 | Inter(1,1) | A={8,7,6,9} |
2 | 3 | Inter(2,3) | A={8,7,9,6} |
4 | 3 | Inter(3,3) | A={8,7,9,6} |