The division algorithm
Find the quotient q and remainder r with a = q·b + r and 0 ≤ r < b, by subtracting or adding b again and again.
The division theorem: for every integer a and every b > 0 there is exactly one pair q, r with
- Time:
O(|a| / b) - Space:
O(1) - Grimaldi, chapter 4
- Johnsonbaugh, chapter 5
170 divided by 11: 170 = 15·11 + 5.
def divide(a, b):# a = q·b + r with 0 ≤ r < b, by repeated subtraction (b > 0).q = 0r = arows = [(q, r)]while r >= b:r = r - bq = q + 1rows.append((q, r))while r < 0:r = r + bq = q - 1rows.append((q, r))return q, r
Start
The table is still empty.
Local variables
Orange = changed in this step
Call stack
- divide()line 1
Explanation
The idea
The division theorem: for every integer a and every b > 0 there is exactly one pair q, r with
a = q·b + r and 0 ≤ r < b
The simplest way to find them: start with q = 0 and r = a. While r ≥ b, take one b away and add one to q; if
a was negative, while r < 0, add one b and take one from q.
A note on negative numbers
In mathematics the remainder is never negative, so −17 mod 5 = 3. Some programming languages (such as C) give −2;
Python gives 3, like mathematics.
Cost
This takes |a| / b steps; machines divide directly and much faster. The point here is to see what q and r mean.