Recitation 8 should be submitted following directions at:
submissions with deadlines
|
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. |