Algorithm: div Inputs: a, b where a>=0 and b>0 Output: q and r such that a = q*b + r, and 0 ≤ r < b if a < b q = 0, r = a else q',r' = div(a-b,b) q = q'+1, r = r' return q,r
Just to make sure you understand how this works, here's an example:
a b q' r' q r
---------------------
initial call is div(27,6) 27 6 3 3 4 3
makes a call to div(21,6) 21 6 2 3 3 3
makes a call to div(15,6) 15 6 1 3 2 3
makes a call to div(9,6) 9 6 0 3 1 3
makes a call to div(3,6) 3 6 - - 0 3
The first three lines of the algorithm (before any actual steps to execute) are what is called the specification of the algorithm. It tells you what kinds of inputs are allowed, and what properties the outputs will satisfy. After that is the body of the algorithm. We can't just assume that the algorithm actually accomplishes what the specification states. We need to prove it! We need to prove that if we give two integers $a$ and $b$ that satisfy the requirements that $a \geq 0$ and $b > 0$, then $\text{div}(a,b)$ will return $p$ and $q$ such that $a = q*b+r$ and $0\leq r \lt b$. We are going to want to do this by induction, but that means that we need to define what the "size" of $\text{div}(a,b)$ is. We are going to adopt a somewhat strange idea of size:
size of $\text{div}(a,b)$ is 0 if $a \lt b$ and $1 + a - b$ otherwise
To get an idea of what this means, let's see the sizes of the calls to div in the above example:
a b q' r' q r size
---------------------
initial call is div(27,6) 27 6 3 3 4 3 22 ← 1 + 27 - 6
makes a call to div(21,6) 21 6 2 3 3 3 16 ← 1 + 21 - 6
makes a call to div(15,6) 15 6 1 3 2 3 10 ← 1 + 15 - 6
makes a call to div(9,6) 9 6 0 3 1 3 4 ← 1 + 9 - 6
makes a call to div(3,6) 3 6 - - 0 3 0 ← a < b
Notice how the sizes get smaller and smaller with each
successive call to div, and that it bottoms out at size 0.
That shows us that we have chosen a good definition of "size".
ACTIVITY ← verifying the correctness of the above proof!
Here's an important question that you probably never considered in grade school math: are the quotient and remainder unique? Or are there choices? For example: if a=27 and b=6, the quotient is 4 and remainder is 3, since: 27 = 4*6 + 3. But are there other choices? It turns out the answer is "no"!
Warning! Everyone agrees on the definition
of quotient and remainder when neither $a$ nor $b$ are
negative. However, there are at least three different
definitions out there when negative values come into play
... and that includes different ideas from different
programming languages. Note that in C++, the '/' operator
on objects of type int is for quotient, the '%'
operator is for remainder. In Python, the '//' operator is
for quotient and '%' is for remainder.
sign of q,r for SI242
a > 0 a < 0
b > 0 q+,r+ q-,r+
b < 0 q-,r+ q+,r+ |
sign of q,r for C++
a > 0 a < 0
b > 0 q+,r+ q-,r-
b < 0 q-,r+ q+,r- |
sign of q,r for Python
a > 0 a < 0
b > 0 q+,r+ q-,r+
b < 0 q-,r- q+,r- |
-27 6 -27 = -5*6 + 3