Workbench / Mathematics Book 1 Companion: Arithmetic and Numbers
B1·05
Factors, Multiples and Primes
Around chapter 5: how divisibility, primes and the gcd connect to fractions, hashing, check digits and cryptography; three other ways to see them; what the chapter simplifies (gcd of zero, square roots of big numbers, powers in floating point); how Python's Fraction finds the best simple approximation to π with Euclid's algorithm; four debugging drills; and interview questions.
Understanding it better
Concept map
- Divides (: remainder 0) → factors and multiples → divisibility tests, all from place value: last digits for factors of , digit sums for 3 and 9 (), alternating sums for 11 ().
- Remainders add and multiply → congruence → modular arithmetic: clocks, calendars, hashing, check digits, cryptography.
- Primes → infinitely many (Euclid) → thinning like → the fundamental theorem: exactly one factorisation → a prime dividing a product divides a factor.
- gcd and lcm from factorisations, or the gcd by Euclid's algorithm without factorising → lowest terms (chapter 6), schedules, coprimality.
- Factoring is hard, testing primality and computing gcds are easy → public-key cryptography.
- Software: hash table sizes, sharding, check digits,
math.gcd,pow(a, b, m), key generation.
Explain it differently
Tiles in rectangles. A number's factors are the side lengths of every rectangle its tiles can make; a prime's tiles only make a single row. The gcd of 1071 and 462 is the side of the largest square tile that exactly fills a 1071 × 462 rectangle; Euclid's algorithm cuts off the biggest squares it can, again and again, until the leftover strip is filled by squares exactly (a 21-unit square, here).
Two gear wheels. A 12-tooth gear driving an 18-tooth gear returns to its starting position together after teeth have passed: 3 turns of the small one, 2 of the big one. Gear designers choose coprime tooth counts so that every tooth meets every other tooth, spreading wear.
Locks and keys. Multiplying two primes is snapping a padlock shut: anyone can do it. Factoring the product is opening it without the key. Public-key cryptography publishes the shut padlock and keeps the primes.
Gaps and misconceptions
What the chapter oversimplifies
1. "The gcd is the largest number dividing both", which breaks down at zero. Every number divides 0, so "the largest number dividing 0 and 0" doesn't exist. By convention , and , which keeps Euclid's algorithm and every formula working. Code that divides by a gcd must handle it:
import math
print(math.gcd(0, 0), math.gcd(0, 12), math.gcd(-12, 18), math.lcm(0, 12))
def lowest_terms(a, b):
g = math.gcd(a, b)
return a // g, b // g
print(lowest_terms(6, 8), lowest_terms(0, 5))
try:
print(lowest_terms(0, 0))
except ZeroDivisionError as e:
print("ZeroDivisionError:", e)
0 12 6 0
(3, 4) (0, 1)
ZeroDivisionError: integer division or modulo by zero
math.gcd also takes absolute values (), and . Reducing divides by 0; reducing gives , the standard form of zero. Drill D1.
2. "Try divisors up to ", where both "up to" and "" hide traps in code. "Up to" must include itself (25 has only the divisor 5), and computed in floating point is wrong for large perfect squares:
import math
for n in [10**8 + 7, 2**26 + 1, 2**52 + 1, 10**17 + 3]:
sq = n * n
print(n, int(math.sqrt(sq)) == n, math.isqrt(sq) == n)
100000007 True True
67108865 True True
4503599627370497 True True
100000000000000003 False True
For , math.sqrt of its square rounds, and int of it isn't ; math.isqrt (an exact integer square root) always is. Drills D2 and D3.
3. "Remainders multiply", which in code only helps if you take them as you go. is easy by hand with remainders: reduce after every multiplication. Computing first and then the remainder works in Python (exact integers) but not in JavaScript, where is a rounded float:
console.log(7 ** 30 % 13, Number(7n ** 30n % 13n));
function powMod(a, b, m) { // square and multiply, reducing as we go
let result = 1n, base = BigInt(a) % BigInt(m), e = BigInt(b), mod = BigInt(m);
while (e > 0n) { if (e & 1n) result = result * base % mod; base = base * base % mod; e >>= 1n; }
return result;
}
console.log(powMod(7, 30, 13), powMod(2, 1000, 1000007));
1 12
12n 783922n
The float route gives 1; the true remainder is 12. Square-and-multiply with a reduction after every step (Python's built-in pow(7, 30, 13)) keeps every number smaller than the modulus squared. Drill D4.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "The gcd of 0 and 0 is undefined, so code can ignore it." | By convention it's 0, and dividing by it fails; handle zero explicitly. | What the chapter oversimplifies, point 1; drill D1 |
"range(2, int(sqrt(n))) tries every divisor up to the square root." |
It stops one short: 4, 9, 25 and 143 are reported prime. | Drill D2 |
"int(math.sqrt(n)) is the integer square root." |
Only while is small enough for floats; use math.isqrt. |
What the chapter oversimplifies, point 2; drill D3 |
"a ** b % m is fine for modular powers." |
The power can be huge or rounded; reduce as you go with pow(a, b, m). |
What the chapter oversimplifies, point 3; drill D4 |
| "Euclid's algorithm is only for gcds." | Its quotients are the continued fraction of a/b, which finds the best simple fractions near any number (22/7, 355/113 for π). | Code walkthrough |
Theoretical gaps: the ideas behind the chapter
- Rings and units: the remainders modulo form a number system of their own; a remainder has a multiplicative inverse exactly when it's coprime to (Bézout). When is prime, every non-zero remainder has one, so you can divide: the system is a field. Cryptography and error-correcting codes are built on such fields.
- Why unique factorisation isn't obvious: in some number systems it fails (in numbers of the form , with all four factors "prime"). The proof in the chapter uses a property of whole numbers (division with a smaller remainder) that those systems lack.
- Complexity: computing a gcd takes a number of steps proportional to the number of digits; testing primality takes polynomial time (the AKS test, 2002, proved it deterministically); factoring has no known polynomial-time algorithm on ordinary computers. That gap, not any single theorem, is what cryptography rests on.
Applying it
Code walkthrough
Python's Fraction keeps every fraction in lowest terms by dividing by the gcd, and its limit_denominator method finds the closest fraction to a number whose denominator is no bigger than a limit ( for π with denominators up to 10). The method's core loop is Euclid's algorithm. Excerpts from Lib/fractions.py in Python 3.13 (on your computer: python3 -c "import fractions; print(fractions.__file__)").
if max_denominator < 1:
raise ValueError("max_denominator should be at least 1")
if self._denominator <= max_denominator:
return Fraction(self)
p0, q0, p1, q1 = 0, 1, 1, 0
n, d = self._numerator, self._denominator
while True:
a = n//d
q2 = q0+a*q1
if q2 > max_denominator:
break
p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
n, d = d, n-a*d
k = (max_denominator-q0)//q1
Look at the first and last lines of the loop: a = n//d and n, d = d, n-a*d. That's Euclid's algorithm: divide, keep the quotient, replace the pair by (divisor, remainder). The quotients are the terms of the continued fraction of , and p1/q1 accumulates the fraction they describe, stopping just before the denominator would pass the limit. The code after the loop (not shown) decides between two final candidates. Measured:
from fractions import Fraction
import math
def quotients(n, d):
"""The same loop as limit_denominator: a = n // d, then (n, d) = (d, n - a*d). It is Euclid's algorithm."""
out = []
while d:
a = n // d
out.append(a)
n, d = d, n - a * d
return out, n # the quotients, and the last divisor: the gcd
print(quotients(1071, 462))
print(Fraction(1071, 462), Fraction(math.pi).limit_denominator(10), Fraction(math.pi).limit_denominator(1000))
print(quotients(*Fraction(math.pi).as_integer_ratio())[0][:6])
([2, 3, 7], 21)
51/22 22/7 355/113
[3, 7, 15, 1, 292, 1]
Euclid's quotients for 1071 and 462 are 2, 3, 7, the same three divisions as the chapter's example, with gcd 21; that's why Fraction(1071, 462) is (both divided by 21). For π (the float's exact fraction), the quotients begin 3, 7, 15, 1, 292: stopping after "3, 7" gives ; after "3, 7, 15, 1" gives , accurate to six decimal places, found by the Chinese mathematician Zu Chongzhi in the fifth century. The huge next term, 292, is why is so unusually good: the next improvement is a long way off.
Read it yourself
Using the loop above, explain why it must stop, and why the denominators q1 it produces keep growing. Then predict the quotients for and the fractions p1/q1 the loop passes through.
Debugging drills
D1. A fraction-reducing function that crashed on empty data
A reporting tool shows ratios such as "orders shipped : orders placed" in lowest terms, using the lowest_terms function in "What the chapter oversimplifies", point 1. On a day with no orders at all it crashes. Explain, and fix it so it behaves sensibly for every input.
D2. A prime test that lets squares through
A colleague's is_prime (code in the output below) passes a few spot checks, but a property test finds many composites it calls prime:
def is_prime(n):
"""First attempt: try divisors up to the square root."""
if n < 2:
return False
for d in range(2, int(n ** 0.5)):
if n % d == 0:
return False
return True
print("reported prime but aren't, below 200:", [n for n in range(200) if is_prime(n) and any(n % d == 0 for d in range(2, n))])
reported prime but aren't, below 200: [4, 6, 8, 9, 15, 25, 35, 49, 121, 143, 169]
Explain the pattern in the list and fix the function.
D3. A factoriser that's wrong only for huge numbers
A factoring tool uses int(math.sqrt(n)) as the trial-division limit. It's correct in every test, but for it reports the wrong factorisation. Using the output in "What the chapter oversimplifies", point 2, explain why, and fix it.
D4. A modular power that's right in Python and wrong in JavaScript
A team ports a check-digit routine from Python, where it computes 7 ** 30 % 13, to JavaScript. The JavaScript version disagrees (output in "What the chapter oversimplifies", point 3). Explain, and write the portable fix.
Career-oriented
Interview prep
Mid level
Q1. Write gcd(a, b) and explain why it's fast.
How to get there. The algorithm, why each step preserves the gcd, and a bound on steps.
Q2. Implement is_prime(n) for up to about , and say how you'd test it.
How to get there. Trial division to the square root, the edge cases, and an oracle.
Senior level
Q1. You're designing an order-reference format that customers type into a support chat. How do you protect against typos?
How to get there. Which errors people make, which schemes catch them, and the cost.
Q2. Your service's cache uses hash(key) % N with , and one node is overloaded. The keys are product IDs that are all multiples of 64. What's happening?
How to get there. Remainders keep shared factors.
Staff level
Q1. A security review asks whether your system's RSA keys need replacing. What do you check and recommend?
How to get there. Key sizes, generation quality, algorithms in use, and the quantum timeline.
Q2. Your team uses modulo arithmetic in many places (sharding, rate-limit windows, retry jitter, IDs). What standards would you set?
How to get there. The recurring failure modes across the chapter and its exercises.