Volume 1: Foundations to Precalculus · Part I: Foundations
Chapter 1. Numbers, the Number Line, and Arithmetic
Chapter map: we begin where everything begins — with numbers. Not to relearn how to add, but to reconnect the arithmetic you can already do with the vocabulary, structure, and reasons behind it. We will see why number systems kept having to grow, how place value makes arithmetic (and computers) work, which laws of arithmetic quietly power all of algebra, why a negative times a negative must be positive, why "order of operations" is a convention rather than a law of nature, and how fixed-width integers in a computer behave differently from the integers of mathematics.
Why it matters: every quantity you will ever compute with (a bank balance, a sensor reading, a pixel coordinate, a 64-bit counter) lives in one of these number systems, and most arithmetic bugs, in spreadsheets and in production code alike, come from a value obeying different rules from the ones you assumed. This chapter is where those rules are made explicit.
1.1. Kinds of number
1.1.1. The problem
Suppose you only had the counting numbers 1, 2, 3, … . You could count sheep, but you could not:
-
say how many sheep are in an empty field;
-
record that you owe someone three sheep;
-
share two sheep fairly among three people;
-
state the exact length of the diagonal of a square field whose sides are 1 kilometre.
Each of these is a perfectly ordinary question, and each one breaks the number system you had. The history of numbers is largely the history of patching those breaks. Each patch produced a larger system that contains the old one, and each larger system has a name and a symbol you will meet constantly in technical reading.
1.1.2. Intuition: each system fixes a failure of the last
Think of it as a sequence of feature requests.
-
Counting gives the natural numbers. You can add and multiply them freely and always stay inside.
-
Subtraction fails: \(3 - 5\) has no answer among counting numbers. Fix: add zero and the negatives. Now you have the integers.
-
Division fails: \(2 \div 3\) has no answer among integers. Fix: allow ratios of integers. Now you have the rational numbers.
-
Measuring fails: the diagonal of a unit square has length \(\sqrt{2}\), and (as we will prove) no ratio of integers squares to exactly 2. Fix: fill every gap in the line. Now you have the real numbers.
Later in the book (Chapter 15) one more failure — \(x^2 = -1\) has no real solution — will drive one more extension, to the complex numbers.
1.1.3. Vocabulary and notation
Before the vocabulary, one piece of notation. Mathematicians collect objects into sets and write \(x \in S\) to mean "\(x\) is an element of the set \(S\)" (read "x is in S"). The symbol \(\in\) is a stylised Greek epsilon, for the Latin est, "is". Writing \(A \subset B\) means "every element of \(A\) is also an element of \(B\)" (read "A is a subset of B"). We will treat sets properly in Chapter 21; for now these two symbols are all you need.
|
Natural number
The natural numbers are the counting numbers \(0, 1, 2, 3, \ldots\). The set of them is written \(\mathbb{N}\) (a "blackboard bold" N). Whether \(0 \in \mathbb{N}\) is a convention that varies: computer scientists and logicians almost always include 0; some number theorists start at 1. When it matters, authors write \(\mathbb{N}_0\) (with zero) or \(\mathbb{Z}^+\) (positive integers, without zero). This book includes 0. |
|
Integer
An integer is a whole number that may be positive, negative, or zero: \(\ldots, -3, -2, -1, 0, 1, 2, 3, \ldots\). The set is written \(\mathbb{Z}\), from the German Zahlen, "numbers". The integers are closed under addition, subtraction, and multiplication: doing any of those to two integers gives an integer. |
|
Rational number
A rational number is any number that can be written as a ratio \(\dfrac{p}{q}\) of integers \(p\) and \(q\) with \(q \neq 0\). The set is written \(\mathbb{Q}\), for quotient. Examples: \(\tfrac{1}{2}\), \(-\tfrac{7}{3}\), \(5 = \tfrac{5}{1}\), \(0.125 = \tfrac{1}{8}\). In decimal form a rational number either terminates or eventually repeats (shown in Chapter 2). |
|
Irrational number
An irrational number is a real number that is not rational — it cannot be written as a ratio of integers. Its decimal expansion never terminates and never settles into a repeating block. Examples: \(\sqrt{2} = 1.41421356\ldots\), \(\pi = 3.14159265\ldots\), \(e = 2.71828182\ldots\). |
|
Real number
The real numbers, written \(\mathbb{R}\), are all the rational and irrational numbers together: every point on the number line. Every length, every measurement, every point on a continuous scale is a real number. The defining extra property of \(\mathbb{R}\) over \(\mathbb{Q}\) is that it has no gaps (mathematicians call this completeness). |
The systems nest inside one another:
Every natural number is an integer, every integer is rational (\(n = n/1\)), and every rational is real.
1.1.4. Why it works: \(\sqrt{2}\) really is irrational
It is worth seeing why the rationals are not enough, because the argument is short, beautiful, and the template for a whole style of proof (proof by contradiction, Chapter 22).
Suppose, hoping for a contradiction, that \(\sqrt{2} = p/q\) where \(p\) and \(q\) are integers and the fraction is already in lowest terms (no common factor — we can always cancel until this is true). Then
So \(p^2\) is even. The square of an odd number is odd, so \(p\) itself must be even: write \(p = 2k\). Substituting,
So \(q^2\) is even, and therefore \(q\) is even. But now \(p\) and \(q\) are both even, so they share the factor 2 — contradicting "lowest terms". The assumption was impossible: \(\sqrt{2}\) is not a ratio of integers.
|
The scandal of the diagonal
Legend says the Pythagoreans, who believed "all is number" (meaning whole numbers and their ratios), were so disturbed by the irrationality of \(\sqrt{2}\) that they drowned Hippasus of Metapontum for revealing it. The story is almost certainly embellished, but the mathematical shock was real: the Greeks responded by developing geometry largely separately from arithmetic for the next two thousand years. The word "irrational" originally meant simply "not a ratio", not "unreasonable". |
1.1.5. Failure modes
|
Rational does not mean "has a short decimal"
\(\tfrac{1}{3} = 0.333\ldots\) has an infinite decimal expansion but is perfectly rational. Irrationality is about the expansion never repeating, not about it being long. Conversely, a calculator display of \(1.414213562\) is a rational approximation — the calculator cannot store \(\sqrt{2}\) exactly. Nor can your computer (Chapter 2 explains why even \(0.1\) is out of reach for binary floating point). |
1.1.6. Where you’d use this
-
Money. Prices look like decimals but are really integers in disguise: £19.99 is 1999 pence. Payment systems store whole pence or cents (integers, \(\mathbb{Z}\)) precisely so that totals add up exactly; storing money as
floatis a classic bug (Chapter 2). -
Measurement. Every physical length, mass, or time is a real number, but every measurement of it is a rational approximation. A bicycle wheel of diameter 0.7 m rolls \(\pi \times 0.7 \approx 2.199\) m per turn; the exact distance is irrational, so an engineer decides how many digits matter (Section 1.10).
-
Counting things. Stock levels, seats, packets, and array indices are natural numbers. A negative stock level or a fractional seat count is a sign that a value has escaped its proper number system, which makes "which set should this live in?" a useful validation rule for any database column.
1.2. The number line
1.2.1. Intuition
The single most useful picture in elementary mathematics is a straight line with a point marked 0, a point marked 1 to its right, and every real number occupying exactly one point. Positive numbers lie to the right of zero, negatives to the left, and the distance from zero records size.
The line turns arithmetic into motion. Adding 3 means stepping 3 units right. Subtracting 3 means stepping 3 units left. Multiplying by 2 means stretching everything away from zero by a factor of 2; multiplying by \(-1\) means reflecting through zero. You will see these geometric readings return in vectors (Chapter 26) and complex numbers (Chapter 15), where multiplication becomes rotation.
1.2.2. Vocabulary and notation
|
Order and inequality symbols
\(a < b\) means "\(a\) is less than \(b\)": \(a\) lies to the left of \(b\) on the number line. \(a > b\) means "greater than". \(a \le b\) means "less than or equal to", \(a \ge b\) "greater than or equal to", and \(a \neq b\) "not equal to". The narrow end of \(<\) points at the smaller number. A number is positive if it is \(> 0\), negative if \(< 0\), and non-negative if \(\ge 0\); zero is neither positive nor negative. |
Two facts about the line deserve to be said out loud, because they become important in calculus:
-
Density. Between any two different rational numbers there is another one (their average). So there is no "next" rational after 0 — the rationals are packed infinitely tightly.
-
Gaps anyway. Despite that density, the rationals miss points such as \(\sqrt{2}\). The reals fill every gap. This "no gaps" property is exactly what makes limits (Chapter 16) work.
|
Negative numbers and "smaller"
\(-10 < -2\), even though 10 is "bigger" than 2. On the number line \(-10\) is further left. In everyday speech people say "a bigger loss" for \(-10\), which describes magnitude, not order. When order matters, think "further left = less". Magnitude is captured by absolute value (Section 1.7). |
|
Zooming the number line
A number line you can zoom indefinitely. Mark \(\sqrt{2}\) and keep zooming: each zoom reveals another decimal digit, and the nearest rational points with small denominators (\(\tfrac{7}{5}\), \(\tfrac{17}{12}\), \(\tfrac{41}{29}\), …) light up and are left behind, but the point itself never lands on a rational. Try it: Best fractions for √2 |
1.3. Place value and number bases
1.3.1. The problem
Write down the number of seconds in a year. You probably wrote something like 31536000, and you did not need a new symbol for it. Compare Roman numerals: XXXI million … there is no good way. The reason modern notation handles any size with only ten symbols is place value: the meaning of a digit depends on its position. Understanding place value precisely lets you work in any base — and base 2 and base 16 are the native tongues of computers.
1.3.2. Intuition
In 2047 the "2" means two thousands, the "0" means no hundreds, the "4" means four tens, and the "7" means seven ones. Each position is worth ten times the position to its right. Nothing is special about ten except that we have ten fingers. Make each position worth two times the one to its right, and you have binary; sixteen, and you have hexadecimal.
1.3.3. Why it works
In base \(b\) a digit string \(d_{k} d_{k-1} \ldots d_1 d_0\) (each digit \(d_i\) between 0 and \(b-1\)) stands for
Here \(b^k\) means \(b\) multiplied by itself \(k\) times, and \(b^0 = 1\) (powers are the subject of Chapter 3, which also explains why \(b^0 = 1\)). The subscripts on \(d_i\) are labels, not exponents: \(d_0\) is "the digit in position 0", the rightmost one.
Every non-negative integer has exactly one such representation (without leading zeros). The reason is division with remainder: dividing by \(b\) peels off the last digit as the remainder and shifts the rest down one position as the quotient. Repeat until nothing is left.
1.3.4. Vocabulary and notation
|
Base, digit, and positional notation
The base (or radix) \(b\) of a positional system is how many times larger each position is than the one to its right. A digit is one of the symbols \(0, 1, \ldots, b-1\). Positional (or place-value) notation means a digit’s value is the digit times \(b^{\text{position}}\), counting positions from 0 at the right. When the base is not obvious we write it as a subscript: \(101101_2 = 45_{10}\). |
|
Binary, bit, byte, hexadecimal
Binary is base 2, with digits 0 and 1. A single binary digit is a bit; eight bits make a byte. Hexadecimal ("hex") is base 16, with digits \(0\text{–}9\) then A=10, B=11, C=12, D=13, E=14, F=15. Because \(16 = 2^4\), each hex digit corresponds to exactly four bits (a nibble). Octal is base 8 (three bits per digit). Programming languages mark bases with prefixes: |
1.3.5. The method
Input: a non-negative integer \(n\) and a base \(b \ge 2\).
Steps:
-
If \(n = 0\), the answer is "0". Stop.
-
Divide \(n\) by \(b\), obtaining quotient \(q\) and remainder \(r\) (so \(n = qb + r\) with \(0 \le r < b\)).
-
Record \(r\) as the next digit, working from right to left.
-
Replace \(n\) by \(q\). If \(n > 0\), go back to step 2.
Output: the recorded digits, read in reverse order of discovery (last remainder is the leftmost digit).
Input: digits \(d_k, d_{k-1}, \ldots, d_0\) (left to right) and base \(b\).
Steps:
-
Set \(v = 0\).
-
For each digit \(d\), from left to right: set \(v = v \cdot b + d\).
Output: \(v\), the value.
Horner’s rule avoids computing powers at all: each step "shifts left one place" by multiplying by \(b\) and then drops the new digit into the empty units position.
1.3.6. Worked examples
Example 1: 45 to binary. Divide repeatedly by 2.
Reading the digits from \(d_5\) down to \(d_0\): \(45_{10} = 101101_2\). Check by expanding: \(32 + 0 + 8 + 4 + 0 + 1 = 45\). ✓
Example 2: 2047 to hexadecimal.
So \(2047_{10} = \text{7FF}_{16}\). Check: \(7 \times 256 + 15 \times 16 + 15 = 1792 + 240 + 15 = 2047\). ✓
Example 3: \(\text{2D}_{16}\) to decimal by Horner’s rule. Start with \(v = 0\). Digit 2: \(v = 0 \times 16 + 2 = 2\). Digit D (=13): \(v = 2 \times 16 + 13 = 45\). So \(\text{2D}_{16} = 45\).
1.3.7. Alternative approach: grouping bits
Between binary and hex (or octal) there is a much faster route than going via decimal. Since one hex digit is exactly four bits, group the binary digits in fours from the right and translate each group:
(The underbrace labels what each group of four bits becomes.) Going the other way, expand each hex digit into four bits: \(\text{7FF}_{16} = 0111\;1111\;1111_2\).
The other common method for decimal-to-binary is subtracting powers of two: find the largest power of two not exceeding \(n\), write a 1 there, subtract, repeat. For 45: \(32\) fits (remainder 13), 16 does not, 8 fits (remainder 5), 4 fits (remainder 1), 2 does not, 1 fits. Digits 101101 again.
1.3.8. Choosing a method
-
Binary ↔ hex or octal: always group bits. It is mechanical and nearly error-free.
-
Decimal → binary for small numbers you can see the powers of 2 in (anything under about 1000): subtract powers of two — it is the fastest mental method.
-
Decimal → any base for larger numbers, or in code: repeated division.
-
Any base → decimal: Horner’s rule, which is also how every
parseIntis written.
1.3.9. Implementation
DIGITS = "0123456789ABCDEF"
def to_base(n, b):
"""Return the base-b digit string of a non-negative integer n (2 <= b <= 16)."""
if n == 0:
return "0"
digits = []
while n > 0:
n, r = divmod(n, b) # quotient and remainder in one step
digits.append(DIGITS[r]) # remainders come out least-significant first
return "".join(reversed(digits))
def from_base(s, b):
"""Inverse: evaluate a digit string in base b (Horner's rule)."""
value = 0
for ch in s:
value = value * b + DIGITS.index(ch.upper())
return value
print(to_base(45, 2), to_base(2047, 16), to_base(255, 2))
print(from_base("101101", 2), from_base("7FF", 16), int("7FF", 16))
101101 7FF 11111111 45 2047 2047
Python’s built-ins bin, hex, oct, int(s, base), and format strings such as f"{45:08b}" do the same jobs; the point of writing them yourself once is to see that they are just the two procedures above.
|
A leading zero that changes the number
In C, C++, Java, and JavaScript (non-strict mode), an integer literal with a leading zero is octal: |
|
Base 60 is still on your wrist
The Babylonians used base 60 around 2000 BCE, with a place-value system but (for a long time) no zero symbol, so they had to infer from context whether a gap meant "nothing in this place". We still inherit their base in 60 seconds per minute, 60 minutes per hour, and 360 degrees in a circle. Sixty is convenient because it divides evenly by 2, 3, 4, 5, 6, 10, 12, 15, 20, and 30. A true zero digit, acting as a placeholder, was developed in India by about the 7th century CE and reached Europe through Arabic mathematicians — hence "Hindu–Arabic numerals". |
|
Base explorer
Type a number and watch it displayed simultaneously in bases 2, 8, 10, and 16, with each digit’s place value shown as a stack of blocks. Click a bit to toggle it and see the decimal and hex values update; notice that toggling bit \(k\) always changes the value by exactly \(2^k\). Try it: 255 in every base |
1.3.10. Exercises
-
Write \(1011_2\), \(777_8\), and \(\text{FF}_{16}\) in decimal.
-
Convert 100 to binary by repeated division, then convert your answer to hex by grouping bits.
-
A colour is stored as
0x00FF7F. What are its red, green, and blue components in decimal? -
Explain, using the place-value formula, why appending a 0 to the right of a binary numeral doubles its value. What does appending a 0 do in base \(b\)?
Answers
-
\(1011_2 = 8 + 0 + 2 + 1 = 11\). \(777_8 = 7 \cdot 64 + 7 \cdot 8 + 7 = 448 + 56 + 7 = 511\). \(\text{FF}_{16} = 15 \cdot 16 + 15 = 255\).
-
\(100 = 50 \cdot 2 + 0\), \(50 = 25 \cdot 2 + 0\), \(25 = 12 \cdot 2 + 1\), \(12 = 6 \cdot 2 + 0\), \(6 = 3 \cdot 2 + 0\), \(3 = 1 \cdot 2 + 1\), \(1 = 0 \cdot 2 + 1\). Reading remainders upward: \(1100100_2\). Grouping from the right: \(0110\;0100 = \text{64}_{16}\). Check: \(6 \cdot 16 + 4 = 100\). ✓
-
Red \(\text{00} = 0\), green \(\text{FF} = 255\), blue \(\text{7F} = 7 \cdot 16 + 15 = 127\). (A spring green.)
-
Appending a digit moves every existing digit up one position, multiplying its place value by the base, and puts 0 in the units place. So in base 2 the value doubles; in base \(b\) it is multiplied by \(b\). This is why a left shift
x << 1multiplies by 2.
1.4. The four operations and their laws
1.4.1. The problem
How do you work out \(17 \times 25\) in your head? Many people do something like "\(17 \times 100 = 1700\), divide by 4, that’s 425." Or "\(17 \times 25 = 10 \times 25 + 7 \times 25 = 250 + 175 = 425\)." Both are correct. But why are you allowed to do that? Neither is the long-multiplication algorithm you were taught.
The answer is a handful of laws that addition and multiplication obey. They look so obvious that it is easy to skip past them — but they are the entire rulebook of algebra. Every time you "simplify", "expand", "factor", "collect like terms", or "move something to the other side", you are applying one of these laws. Knowing them by name means you can justify every step you take, and spot the step that is not justified.
1.4.2. Vocabulary and notation
|
Sum, difference, product, quotient
The result of an addition is a sum; its inputs are terms (or addends). The result of a subtraction is a difference. The result of a multiplication is a product; its inputs are factors. The result of a division is a quotient: in \(a \div b\), \(a\) is the dividend and \(b\) the divisor. Multiplication may be written \(a \times b\), \(a \cdot b\), or simply \(ab\) when at least one factor is a letter. |
|
Commutative, associative, distributive
An operation is commutative if order of the inputs does not matter: \(a + b = b + a\), \(ab = ba\). It is associative if grouping does not matter: \((a + b) + c = a + (b + c)\), \((ab)c = a(bc)\). Multiplication distributes over addition: \(a(b + c) = ab + ac\). Mnemonic: commute = move around; associate = who you group with; distribute = hand out to each. |
|
Identity and inverse
An identity element for an operation leaves things unchanged: \(a + 0 = a\) (0 is the additive identity), \(a \times 1 = a\) (1 is the multiplicative identity). An inverse undoes: \(-a\) is the additive inverse (or opposite) of \(a\) because \(a + (-a) = 0\); \(\tfrac{1}{a}\) is the multiplicative inverse (or reciprocal) of \(a \neq 0\) because \(a \cdot \tfrac{1}{a} = 1\). |
Collected in one place, for all real numbers \(a, b, c\):
1.4.3. Intuition
The distributive law is the one that does the heavy lifting, and it has a lovely picture: a rectangle of height \(a\) and width \(b + c\) has the same area as two rectangles of widths \(b\) and \(c\) placed side by side.
Commutativity of multiplication has a picture too: a grid of 3 rows of 5 dots is the same grid as 5 columns of 3 dots, just turned sideways.
1.4.4. What about subtraction and division?
Subtraction and division are not commutative (\(5 - 3 \neq 3 - 5\), \(6 \div 2 \neq 2 \div 6\)) and not associative:
The clean way to think about this — and the way algebra will treat it — is that subtraction and division are not really separate operations. They are addition and multiplication by an inverse:
Rewrite every subtraction as "add the opposite" and every division as "multiply by the reciprocal", and you are back in the world where everything commutes and associates. \(8 - 4 - 2\) becomes \(8 + (-4) + (-2)\), which you can group and reorder however you like.
1.4.5. Why these laws matter later
When you solve \(3x + 5 = 20\) in Chapter 5, the steps are:
You would never write it out this laboriously in practice. But every "move it to the other side" is secretly this chain. When you meet matrices (Chapter 27), multiplication will stop being commutative (\(AB \neq BA\) in general), and suddenly it matters a great deal which laws you were relying on. Mathematicians give names to structures by which laws they obey: a set with \(+\) and \(\times\) obeying all of the laws above is called a field. \(\mathbb{Q}\) and \(\mathbb{R}\) are fields; \(\mathbb{Z}\) is not (2 has no integer reciprocal).
1.4.6. Worked example: mental arithmetic as applied algebra
Compute \(98 \times 7\) mentally, justifying each step.
Compute \(4 \times 37 \times 25\).
The second example shows why these laws are really about freedom: you are allowed to choose the order that makes the work easy.
1.4.7. Where you’d use this
-
Shopping and tipping. Four items at £2.99: \(4 \times 2.99 = 4 \times (3 - 0.01) = 12 - 0.04 = 11.96\) (distributive law). A 15% tip on a $46 bill: 10% is $4.60 and 5% is half of that, $2.30, so the tip is $6.90, because \(0.15 \times 46 = (0.10 + 0.05) \times 46\).
-
Mechanics. A constant force of 30 N pushes a crate 4 m and then a further 6 m. The work done is \(30 \times 4 + 30 \times 6 = 30 \times (4 + 6) = 300\) J. Factoring out the common force is the distributive law, and it is why physicists can add displacements first and multiply once.
-
Compilers and databases. An optimising compiler rewrites
x*8 + x*2asx*10(distributive law) and(x*4)*25asx*100(associative law). A database evaluatingSUM(price * 1.2)may compute1.2 * SUM(price)instead: one multiplication instead of a million. Both rewrites are legal for integers and real numbers, and only approximately legal for floats, which is exactly the subject of the sidebar below.
1.4.8. Division by zero
|
Why you cannot divide by zero
"\(a \div b = c\)" means "\(c\) is the number with \(c \times b = a\)". Try \(6 \div 0 = c\): we need \(c \times 0 = 6\), but anything times 0 is 0, so no \(c\) works. Try \(0 \div 0 = c\): we need \(c \times 0 = 0\), and every \(c\) works, so there is no single answer. Either way, division by zero has no sensible value, so it is left undefined. Zero is the one real number with no reciprocal. Many algebra "proofs" that \(1 = 2\) hide a division by an expression that equals zero. |
Try it: Sum in different orders.
|
Why "distributive"?
The names "commutative" and "distributive" were coined by the French mathematician François-Joseph Servois in 1814; "associative" came from William Rowan Hamilton in the 1840s, who needed the word because he had just invented the quaternions, a number system in which multiplication is associative but not commutative. Until people built systems where the laws failed, nobody had needed names for them. |
|
Laws as tiles
Drag the dividing line in a \(a \times (b + c)\) rectangle and watch the two partial areas and their sum update. Then switch to "floating-point mode": generate a random list of 1,000 floats, sum it in forward, reverse, and shuffled order, and display the differing totals. |
1.4.9. Exercises
-
Name the law used in each step: (a) \(3 + x = x + 3\); (b) \(2(x + 5) = 2x + 10\); (c) \((5 \cdot x) \cdot 2 = 5 \cdot (x \cdot 2)\).
-
Compute \(999 \times 6\) and \(25 \times 48\) mentally, writing down the law behind each step.
-
Show by example that division is not associative.
-
Expand \((a + b)(c + d)\) using only the distributive law (twice), and draw the matching area picture.
Answers
-
(a) Commutative law of addition. (b) Distributive law. (c) Associative law of multiplication.
-
\(999 \times 6 = (1000 - 1) \times 6 = 6000 - 6 = 5994\) (distributive). \(25 \times 48 = 25 \times (4 \times 12) = (25 \times 4) \times 12 = 100 \times 12 = 1200\) (associative).
-
\((16 \div 4) \div 2 = 4 \div 2 = 2\), but \(16 \div (4 \div 2) = 16 \div 2 = 8\).
-
Treat \((a + b)\) as a single number and distribute it over \(c + d\): \((a + b)(c + d) = (a + b)c + (a + b)d\). Distribute again (with commutativity to put the factor on the left): \(= ac + bc + ad + bd\). The picture is a rectangle of width \(a + b\) and height \(c + d\) cut into four smaller rectangles. This is the origin of "FOIL", which Chapter 7 generalises.
1.5. Negative numbers
1.5.1. The problem
A bank account holds $40 and you write a cheque for $70. The balance is \(-30\). The temperature is \(-5^\circ\text{C}\) and falls by 8 degrees: it is now \(-13^\circ\text{C}\). These are easy. But what is \((-3) \times (-4)\)? School says 12 — "two negatives make a positive" — but if you were never told why, the rule feels arbitrary, and arbitrary rules are the ones that get misremembered.
1.5.2. Intuition: adding and subtracting on the line
On the number line, a negative number is a step to the left.
-
\(5 + (-8)\): start at 5, step 8 left, land on \(-3\).
-
\(5 - 8\): the same thing, since \(a - b = a + (-b)\).
-
\(5 - (-8)\): "subtracting a step to the left" — undoing a debt — is a step to the right: \(5 - (-8) = 5 + 8 = 13\).
The last one is just the observation that the opposite of the opposite is the original: \(-(-8) = 8\), because 8 is the number that, added to \(-8\), gives 0.
1.5.3. Why negative times negative is positive
There are two good arguments. The first is a pattern argument that convinces; the second is an algebraic argument that proves.
Pattern. Multiply \(-2\) by a factor that decreases by 1 each line:
The first four lines are uncontroversial (\(3 \times (-2)\) is three debts of 2). Each time the first factor drops by 1, the product rises by 2. If the pattern continues — and anything else would put a kink in a straight line — then \((-1) \times (-2) = 2\) and \((-2) \times (-2) = 4\).
Proof from the laws. The pattern is persuasive, but here is the real reason: if we want the distributive law to keep working for negative numbers, we have no choice. We use only the laws from Section 1.4.
First, anything times zero is zero. For any number \(a\):
Now the main event. Start from something we know is zero and expand it two ways:
Putting the two lines together, \(-1 + (-1)(-1) = 0\). So \((-1)(-1)\) is the number that, added to \(-1\), gives zero. That number is 1. Hence
The general case follows by writing \(-a = (-1)a\): \((-a)(-b) = (-1)(-1)ab = ab\).
The moral: "negative times negative is positive" is not a rule someone chose. It is forced by the distributive law. Any other answer would break the arithmetic that lets you expand brackets.
1.5.4. The method
Input: a product or quotient of signed numbers.
Steps:
-
Ignore the signs and compute with the sizes (absolute values).
-
Count the negative factors (dividing by a negative counts as a negative factor).
-
If the count is even, the result is positive; if odd, negative.
Output: the signed result.
Worked example. \(\dfrac{(-6) \times 4 \times (-5)}{-3}\). Sizes: \(6 \times 4 \times 5 / 3 = 120 / 3 = 40\). Negatives: \(-6\), \(-5\), \(-3\) — three, odd. Result: \(-40\).
1.5.5. Where you’d use this
-
Everyday. The temperature rises from \(-5^\circ\text{C}\) overnight to \(3^\circ\text{C}\) at noon: the change is \(3 - (-5) = 8\) degrees. A golfer at \(-3\) (three under par) who scores \(+2\) on the next hole is at \(-1\).
-
Physics. In mechanics a sign encodes a direction. Take "up" as positive and throw a ball upward at 12 m/s; gravity gives an acceleration of \(-9.8\ \text{m/s}^2\). After 2 seconds the velocity is \(12 + (-9.8)(2) = -7.6\) m/s: the negative sign tells you the ball is now falling. Charge, current direction, and profit/loss work the same way.
-
Computing. Screen coordinates usually have \(y\) increasing downward, so "move up 10 pixels" is \(\Delta y = -10\). Python’s
a[-1]is the last element of a list,a[-2]the one before. File seeks, timezone offsets (UTC \(-5\)), and version diffs are all signed quantities.
1.5.6. Failure modes
|
\(-3^2\) is not \((-3)^2\)
By the standard convention (Section 1.6), exponents bind more tightly than the leading minus sign. So \(-3^2\) means \(-(3^2) = -9\), while \((-3)^2 = 9\). Python agrees: |
Try it: −3² in five conventions.
|
Two minus signs that mean different things
The symbol "−" does two jobs. In \(7 - 3\) it is binary subtraction (two inputs). In \(-3\) or \(-x\) it is unary negation ("the opposite of"). \(-x\) is not necessarily a negative number: if \(x = -5\) then \(-x = 5\). Read \(-x\) as "the opposite of \(x\)", never as "negative \(x\)", and many sign errors disappear. |
|
A latecomer
Negative numbers were used routinely in China (red rods for positive, black for negative) and in India by the 7th century, where Brahmagupta gave the sign rules explicitly in terms of "fortunes" and "debts". European mathematicians resisted them for over a thousand years longer: as late as the 18th century, some respected authors called them "absurd" or "fictitious". Accountants, who had been using red ink for debts all along, were ahead of the mathematicians. |
1.5.7. Exercises
-
Compute: (a) \(-7 + 12\); (b) \(-7 - 12\); (c) \(-7 - (-12)\); (d) \((-7)(-12)\).
-
Compute \((-1)^{5}\), \((-1)^{6}\), and \((-2)^3 \times (-1)^2\).
-
Using the same style as the proof above, show that \((-1) \cdot a = -a\) for any \(a\). (Hint: show \(a + (-1)a = 0\).)
Answers
-
(a) 5. (b) \(-19\). (c) \(-7 + 12 = 5\). (d) 84.
-
Five negative factors (odd): \(-1\). Six (even): \(1\). \((-2)^3 = -8\), \((-1)^2 = 1\), product \(-8\).
-
\(a + (-1)a = 1 \cdot a + (-1)a = (1 + (-1))a = 0 \cdot a = 0\) (identity, distributive, inverse, and the "times zero" fact). So \((-1)a\) is a number which added to \(a\) gives 0 — by definition, that is \(-a\).
1.6. Order of operations
1.6.1. The problem
Every few months an expression such as
goes viral, with half the internet insisting the answer is 16 and the other half insisting it is 1. Who is right? The uncomfortable truth is that the question has no mathematical answer. Order of operations is a convention — an agreement about how to read a string of symbols — and this expression sits exactly where the conventions are ambiguous.
1.6.2. Intuition
A string like \(2 + 3 \times 4\) could mean \((2 + 3) \times 4 = 20\) or \(2 + (3 \times 4) = 14\). Arithmetic itself does not care; it is the notation that needs a rule. The convention that multiplication goes first was adopted because it makes the most common expressions short: polynomials like \(3x^2 + 2x + 1\) would otherwise need brackets everywhere.
1.6.3. The convention
|
Order of operations (precedence)
Precedence says which operations are done first. The standard order is:
US mnemonic: PEMDAS ("Please Excuse My Dear Aunt Sally"). UK: BODMAS or BIDMAS (Brackets, Orders/Indices, Division, Multiplication, Addition, Subtraction). They are the same rule. |
|
Associativity of operators (left/right)
When operators of equal rank appear in a row, operator associativity decides grouping. Subtraction and division are left-associative: \(a - b - c = (a - b) - c\). Exponentiation is right-associative: \(a^{b^c} = a^{(b^c)}\), so \(2^{3^2} = 2^9 = 512\), not \(8^2 = 64\). (This is a different meaning of "associative" from the law in Section 1.4: here it is a parsing rule for notation.) |
1.6.4. The method
Input: an expression with numbers, brackets, and operators.
Steps:
-
Find an innermost pair of brackets and evaluate inside it using steps 2–4. Replace the bracket by its value. Repeat until no brackets remain.
-
Evaluate all exponents, right to left when stacked.
-
Sweep left to right, performing each multiplication or division as you meet it.
-
Sweep left to right, performing each addition or subtraction as you meet it.
Output: a single number.
1.6.5. Worked example
Evaluate \(20 - 3 \times (4 - 1)^2 \div 9 + 2\).
A common mistake is to do all additions before subtractions: \(20 - (3 + 2) = 15\). Wrong — they have equal rank and go left to right.
1.6.6. Alternative approach: the expression tree
Precedence rules are really instructions for building a tree: each operator is a node whose children are its operands. \(2 + 3 \times 4\) is a \(+\) node with children 2 and (a \(\times\) node with children 3 and 4). Evaluate the tree from the leaves upward. Once you see expressions as trees, precedence stops being a list to memorise and becomes a question of "which operator is at the root?" Chapter 4 develops this view.
1.6.7. Back to the viral problem
In \(8 \div 2(2 + 2)\), strict PEMDAS gives \(8 \div 2 \times 4 = 4 \times 4 = 16\). But many mathematicians, physicists, and textbooks treat implied multiplication (juxtaposition, writing \(2(\ldots)\) or \(2x\) with no symbol) as binding more tightly than an explicit \(\div\), so \(1/2x\) means \(1/(2x)\). Under that reading the answer is \(8 \div 8 = 1\). Neither convention is wrong; the expression is simply badly written. Real mathematics avoids \(\div\) entirely after primary school and uses fraction bars, which make grouping visible: \(\dfrac{8}{2}(2 + 2)\) or \(\dfrac{8}{2(2 + 2)}\). Try it: Parse 8÷2(2+2) five ways.
|
Choosing how to write it
If an expression’s meaning depends on a precedence rule that a reasonable reader might not share, add brackets. This applies doubly to code. Brackets are free; misreadings are not. |
1.6.8. Where you’d use this
-
Spreadsheets. To average three test scores in cells holding 70, 80, and 90, typing
=A1+B1+C1/3gives \(70 + 80 + 90/3 = 180\), not 80. The fix is=(A1+B1+C1)/3. This exact bug turns up in real gradebooks and budgets. Try it: See the gradebook bug’s tree. -
Physics formulas. Kinetic energy is \(\tfrac{1}{2}mv^2\): the exponent applies to \(v\) alone. For a 2 kg ball at 3 m/s that is \(\tfrac{1}{2} \times 2 \times 3^2 = 9\) J. Squaring \(mv\) instead gives \(\tfrac{1}{2}(2 \times 3)^2 = 18\) J, which is twice as large and wrong.
-
Finance. Compound interest \(P(1 + r)^n\) needs its brackets: the exponent must apply to the whole growth factor \(1 + r\), not to \(r\) alone (Chapter 3).
Try it: 232: 512 or 64?; Excel’s =-3^2 versus Python.
|
Precedence playground
Type an expression and see its parse tree drawn, with a selector for convention: "strict PEMDAS", "implied multiplication binds tighter", "Python", "C", "Excel". Watch the tree — and the answer — change for \(8 \div 2(2 + 2)\) and \(-3^2\). Try it: Open the Precedence playground |
1.6.9. Exercises
-
Evaluate \(6 + 18 \div 3 \times 2 - 4\).
-
Evaluate \((2 + 3)^2 - 2 + 3^2\).
-
Without brackets, \(2 \times 3 + 4^2 - 1 = 21\). Insert one pair of brackets to make the result (a) 97, (b) 36, (c) 10.
-
What does Python print for
2 ** -1,-2 ** 0.5and(-8) // 3? Explain each.
Answers
-
\(18 \div 3 = 6\), then \(6 \times 2 = 12\); so \(6 + 12 - 4 = 14\).
-
\(5^2 - 2 + 9 = 25 - 2 + 9 = 32\).
-
(a) \(2 \times (3 + 4)^2 - 1 = 2 \times 49 - 1 = 97\). (b) \(2 \times (3 + 4^2 - 1) = 2 \times 18 = 36\). (c) \(2 \times 3 + 4^{(2 - 1)} = 6 + 4 = 10\) (or \((2 \times 3 + 4)^{(2-1)} = 10\)). Brackets change which operation sits at the root of the expression tree; the same symbols can produce very different values.
-
0.5: \(2^{-1} = \tfrac{1}{2}\) (Chapter 3).-1.4142135623730951: parsed as \(-(2^{0.5})\).-3: floor of \(-2.666\ldots\) is \(-3\) (Python floors toward \(-\infty\)).
1.7. Absolute value
1.7.1. The problem
Two sensors read \(-3.2\) and \(1.8\). How far apart are their readings? A stock moved by \(-4\%\); how big was the move? We often need the size of a number without its sign, or the distance between two numbers without caring which is larger.
1.7.2. Intuition and definition
The absolute value of a number is its distance from zero on the number line. Distance is never negative.
|
Absolute value
The absolute value (or magnitude, or modulus) of \(x\), written \(|x|\), is its distance from 0:
\[|x| = \begin{cases} x & \text{if } x \ge 0, \\ -x & \text{if } x < 0. \end{cases}\]
The large brace introduces a piecewise definition: read each line as "this value, under this condition". So \(|5| = 5\), \(|-5| = -(-5) = 5\), \(|0| = 0\). The distance between \(a\) and \(b\) on the line is \(|a - b|\). |
The second line of the definition, \(-x\) when \(x < 0\), trips people up: it looks like it makes things negative. But when \(x\) is negative, \(-x\) (the opposite of \(x\)) is positive. This is the unary-minus point from Section 1.5 again.
1.7.3. Properties
For all real \(a, b\):
The triangle inequality says a detour is never shorter than the direct route. Equality holds when \(a\) and \(b\) have the same sign; when they have opposite signs they partly cancel. It sounds modest but it is one of the most-used inequalities in all of analysis, and it reappears for vectors in Chapter 26.
1.7.4. Worked example
The two sensors: \(|(-3.2) - 1.8| = |-5| = 5\). Equivalently \(|1.8 - (-3.2)| = |5| = 5\): order does not matter, which is exactly why we use absolute value for distance.
Which numbers \(x\) satisfy \(|x - 2| < 3\)? Read it as "the distance from \(x\) to 2 is less than 3". So \(x\) is within 3 of 2: \(-1 < x < 5\). Translating absolute-value inequalities into distance statements is far more reliable than manipulating them symbolically; Chapter 5 returns to this.
1.7.5. Where you’d use this
-
Manufacturing tolerances. A bolt is specified as \(10.00 \pm 0.05\) mm. A bolt of diameter \(d\) passes inspection when \(|d - 10.00| \le 0.05\): 9.97 mm passes (off by 0.03), 10.06 mm fails (off by 0.06). The same test checks a medicine dose, a thermostat, or a bathroom scale.
-
Measuring error. A weather model’s temperature forecasts are off by \(-2\), \(+3\), and \(-1\) degrees. The plain average error is 0, which suggests a perfect forecast. The mean absolute error is \((2 + 3 + 1)/3 = 2\) degrees, which is the honest answer. Machine-learning models are trained against error measures of exactly this form (Chapter 31).
-
Games and robots on a grid. A piece that moves only along rows and columns needs \(|x_1 - x_2| + |y_1 - y_2|\) moves to get from one square to another: from \((2, 7)\) to \((5, 3)\) that is \(3 + 4 = 7\). This Manhattan distance is the standard heuristic in A* path-finding on grid maps.
1.8. Divisibility, primes, and factorisation
1.8.1. The problem
You need to arrange 360 chairs in a rectangular grid. What shapes are possible? You want to schedule something every 12 days and something else every 18 days; when do they coincide? A hash table works best when its size has no small factors in common with patterns in the keys. All of these are questions about how whole numbers break into products — about divisibility.
This section is a working toolkit. The deep theory (modular arithmetic, the Euclidean algorithm, cryptography) is Chapter 23.
1.8.2. Vocabulary and notation
|
Division with remainder
For integers \(a\) and \(b > 0\) there are unique integers \(q\) (the quotient) and \(r\) (the remainder) with
\[a = qb + r, \qquad 0 \le r < b .\]
Example: \(47 = 6 \times 7 + 5\), so dividing 47 by 7 gives quotient 6, remainder 5. In code, |
|
Divides, factor, multiple
\(b\) divides \(a\), written \(b \mid a\) (a vertical bar, read "b divides a"), if the remainder is 0, i.e. \(a = qb\) for some integer \(q\). Then \(b\) is a factor (or divisor) of \(a\), and \(a\) is a multiple of \(b\). So \(3 \mid 12\) and \(5 \nmid 12\). Do not confuse \(b \mid a\) (a true/false statement) with \(b / a\) (a number). |
|
Prime and composite
A prime is a natural number greater than 1 whose only positive divisors are 1 and itself: \(2, 3, 5, 7, 11, 13, \ldots\). A natural number greater than 1 that is not prime is composite: it can be written as a product of two smaller natural numbers. 1 is neither prime nor composite. 2 is the only even prime. |
1.8.3. The fundamental theorem of arithmetic
Every integer greater than 1 can be written as a product of primes, and this product is unique apart from the order of the factors:
Primes are the atoms of multiplication; the prime factorisation is a number’s chemical formula. Existence is easy to see: if a number is not prime, split it into two smaller factors, and keep splitting until every piece is prime. Uniqueness is subtler and is proved in Chapter 23.
|
Why 1 is not prime
If 1 counted as prime, factorisations would not be unique: \(6 = 2 \times 3 = 1 \times 2 \times 3 = 1 \times 1 \times 2 \times 3 \ldots\). Excluding 1 is not a deep fact about 1 — it is a definition chosen so that the fundamental theorem can be stated cleanly. Until the late 19th century, plenty of mathematicians did list 1 as a prime. |
1.8.4. Divisibility tests
Shortcuts for spotting small factors, with the reason each works:
-
2, 5, 10: look at the last digit. Since \(10 = 2 \times 5\), every digit except the last contributes a multiple of 10, so only the units digit decides.
-
4: last two digits form a multiple of 4 (because 100 is a multiple of 4).
-
3 and 9: the digit sum is a multiple of 3 (or 9). Why: \(10 = 9 + 1\), \(100 = 99 + 1\), \(1000 = 999 + 1\), … each power of 10 is "a multiple of 9, plus 1". So
\[\begin{aligned} 2475 &= 2 \cdot 1000 + 4 \cdot 100 + 7 \cdot 10 + 5 \\ &= 2(999 + 1) + 4(99 + 1) + 7(9 + 1) + 5 \\ &= \underbrace{(2 \cdot 999 + 4 \cdot 99 + 7 \cdot 9)}_{\text{multiple of 9}} + (2 + 4 + 7 + 5) . \end{aligned}\]The number and its digit sum (here 18) leave the same remainder on division by 9 — and also by 3. Since 18 is a multiple of 9, so is 2475 (\(= 9 \times 275\)).
-
11: alternating digit sum. Since \(10 = 11 - 1\), powers of 10 alternate between "multiple of 11 plus 1" and "multiple of 11 minus 1". For 9273: \(3 - 7 + 2 - 9 = -11\), a multiple of 11, so \(11 \mid 9273\) (\(= 11 \times 843\)).
1.8.5. The method: trial division
Input: an integer \(n \ge 2\).
Steps:
-
Set the trial divisor \(d = 2\).
-
While \(d \times d \le n\):
-
While \(d \mid n\): record \(d\) as a factor and replace \(n\) by \(n / d\).
-
Increase \(d\) by 1.
-
-
If \(n > 1\) now, record \(n\) — it is prime.
Output: the list of prime factors of the original number, with repetition, in increasing order.
Try it: Trial division, step by step.
Two details make this correct and fast:
-
We never record a composite \(d\). By the time we try, say, \(d = 6\), all factors 2 and 3 have already been divided out, so 6 cannot divide what remains.
-
We can stop at \(\sqrt{n}\). If \(n = ab\) with both factors bigger than \(\sqrt{n}\), then \(ab > \sqrt{n}\sqrt{n} = n\), which is impossible. So any composite \(n\) has a factor no larger than \(\sqrt{n}\). If no \(d\) up to \(\sqrt{n}\) divides \(n\), it is prime. (The test \(d \times d \le n\) is this condition without computing a square root.)
1.8.6. Worked examples
360. Each split in the tree below records one division.
By trial division: \(360 / 2 = 180\), \(180 / 2 = 90\), \(90 / 2 = 45\); 2 no longer divides 45. Try 3: \(45 / 3 = 15\), \(15 / 3 = 5\); 3 no longer divides 5. Try 4: \(4 \times 4 = 16 > 5\), stop. Remaining \(5 > 1\) is prime. So \(360 = 2^3 \cdot 3^2 \cdot 5\).
97. \(\sqrt{97} \approx 9.85\), so only divisors 2 through 9 need checking. 97 is odd (not 2), digit sum 16 (not 3), does not end in 0 or 5 (not 5), and \(97 = 13 \times 7 + 6\) (not 7). (4, 6, 8, 9 cannot divide it if 2 and 3 do not.) So 97 is prime. Try it: Why 97 is prime.
1001. \(1001 = 7 \times 143 = 7 \times 11 \times 13\). (The alternating digit sum \(1 - 0 + 0 - 1 = 0\) would have flagged 11 immediately.)
def factorise(n):
"""Return the prime factors of n >= 2 in ascending order, with repetition."""
factors = []
d = 2
while d * d <= n: # only need to try divisors up to sqrt(n)
while n % d == 0:
factors.append(d)
n //= d
d += 1
if n > 1: # whatever is left is itself prime
factors.append(n)
return factors
print(factorise(360))
print(factorise(1001))
print(factorise(97))
print(factorise(2**10 * 3 * 1_000_003))
[2, 2, 2, 3, 3, 5] [7, 11, 13] [97] [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 1000003]
1.8.7. Choosing a method and its limits
For numbers up to a few million, trial division is instant and is the right tool. Its cost grows like \(\sqrt{n}\) steps: a 20-digit number may need \(10^{10}\) trial divisions, and a 600-digit number is utterly beyond reach. For testing whether a large number is prime (without finding its factors) there are fast probabilistic tests (Miller–Rabin) that you will meet in Chapter 23. For factorising large numbers, no fast method is known — and that is not a gap in this book but a gap in human knowledge on which much of internet security rests.
1.8.8. Where you’d use this
Two quantities fall straight out of factorisations. The least common multiple (LCM) takes each prime to the highest power found in either number; the greatest common divisor (GCD) takes each prime to the lowest power. (Chapter 23 gives a much faster way to find the GCD.)
-
Scheduling. The opening question: one task every 12 days, another every 18. Since \(12 = 2^2 \cdot 3\) and \(18 = 2 \cdot 3^2\), the LCM is \(2^2 \cdot 3^2 = 36\). They coincide every 36 days. The same calculation tells you when two buses with 12- and 18-minute headways leave the depot together again.
-
Tiling. The largest square tile that exactly covers a 360 cm by 270 cm floor has side \(\gcd(360, 270)\). With \(360 = 2^3 \cdot 3^2 \cdot 5\) and \(270 = 2 \cdot 3^3 \cdot 5\), that is \(2 \cdot 3^2 \cdot 5 = 90\) cm, giving a \(4 \times 3\) grid of tiles.
-
Engineering. Two meshing gears with 12 and 18 teeth bring the same pair of teeth together every \(\operatorname{lcm}(12, 18) = 36\) teeth, so any flaw on one tooth keeps hitting the same few teeth on the other. Designers prefer counts with no common factor (a "hunting tooth"): 13 and 18 teeth meet again only after \(13 \times 18 = 234\) teeth, which spreads the wear.
-
Error detection. An ISBN-10 is valid when \(10d_1 + 9d_2 + \cdots + 1 \cdot d_{10}\) is divisible by 11. For 0-306-40615-2 the sum is 132 = \(12 \times 11\), which is valid. Mistype any single digit, or swap two adjacent digits, and the sum stops being a multiple of 11.
|
Factor explorer
Enter a number and watch trial division run step by step: the current divisor, the shrinking value, the growing factor list, and a marker showing \(\sqrt{n}\) where the search may stop. Then plot the number of steps against \(n\) for \(n\) up to a million and see primes (worst case) form the top envelope. Try it: Open the factor explorer · Factorise any number |
1.8.9. Exercises
-
Is 2,345,678 divisible by 2? by 3? by 9? by 11? Justify with the tests.
-
Find the prime factorisation of 1260 and of 2310.
-
Why does trial division never need to try \(d = 15\) separately, in the sense that 15 can never divide the remaining \(n\) when it is reached?
-
How many different rectangular grids (rows × columns, order mattering) can 36 chairs form? Use the factorisation \(36 = 2^2 \cdot 3^2\) to count without listing.
Answers
-
Last digit 8: divisible by 2. Digit sum \(2 + 3 + 4 + 5 + 6 + 7 + 8 = 35\): not a multiple of 3, so neither 3 nor 9. Alternating sum from the right: \(8 - 7 + 6 - 5 + 4 - 3 + 2 = 5\): not a multiple of 11.
-
\(1260 = 2 \cdot 630 = 2^2 \cdot 315 = 2^2 \cdot 3 \cdot 105 = 2^2 \cdot 3^2 \cdot 35 = 2^2 \cdot 3^2 \cdot 5 \cdot 7\). \(2310 = 2 \cdot 3 \cdot 5 \cdot 7 \cdot 11\).
-
By the time \(d = 15\), every factor 3 and every factor 5 has been divided out of \(n\) (at \(d = 3\) and \(d = 5\)). A number with no factor 3 cannot be a multiple of 15.
-
A divisor of 36 has the form \(2^i 3^j\) with \(i \in \{0, 1, 2\}\) and \(j \in \{0, 1, 2\}\): \(3 \times 3 = 9\) divisors. Each divisor \(r\) gives the grid "\(r\) rows × \(36/r\) columns", so there are 9 grids (1×36, 2×18, 3×12, 4×9, 6×6, 9×4, 12×3, 18×2, 36×1). Counting by exponents like this is a first taste of Chapter 24.
1.9. Integers inside a computer: two’s complement and overflow
1.9.1. The problem
In mathematics, \(\mathbb{Z}\) is infinite: you can always add 1. In a computer, an int32 has exactly \(2^{32}\) possible bit patterns. So what happens when you add 1 to the largest one? And how does a register that only holds bits represent \(-5\) at all?
In December 2014 the YouTube view counter for the video "Gangnam Style" approached \(2\,147\,483\,647 = 2^{31} - 1\), the largest value of a signed 32-bit integer. YouTube upgraded the counter to 64 bits before it overflowed. Many systems have not been so lucky; the "Year 2038 problem" is the same story for 32-bit timestamps counting seconds since 1 January 1970.
1.9.2. Intuition: a clock, not a line
A fixed-width integer does not live on a number line; it lives on a circle, like the hours on a clock. With 4 bits there are 16 patterns, \(0000\) to \(1111\). Adding 1 moves one step clockwise. After \(1111\) comes \(0000\) again — the carry out of the top bit is simply lost.
The question is just how to label the 16 positions. Unsigned integers label them 0 to 15. Two’s complement keeps 0 to 7 for the patterns with top bit 0 and labels the other half \(-8\) to \(-1\), so that stepping counter-clockwise from 0 gives \(-1\), \(-2\), … — exactly as on the number line.
1.9.3. Why it works
On the 16-position clock, moving 16 steps brings you back to where you started, so the patterns cannot tell the difference between \(x\) and \(x + 16\) or \(x - 16\). Mathematicians say the arithmetic is modulo 16 (Chapter 23 develops this as modular arithmetic). The pattern for \(-3\) is therefore the same as the pattern for \(16 - 3 = 13 = 1101_2\). Try it: Step past 7 on the clock; −3 is 1101 in 4 bits.
In general, with \(n\) bits, the negative number \(-x\) is stored as the bit pattern of \(2^n - x\). And since \(2^n - x = (2^n - 1 - x) + 1\), and \(2^n - 1\) is all ones (\(1111_2 = 15\)), subtracting \(x\) from all-ones simply flips every bit. Hence the famous rule:
Input: the \(n\)-bit pattern of an integer \(x\).
Steps:
-
Invert every bit (0 ↔ 1). This computes \(2^n - 1 - x\).
-
Add 1, discarding any carry out of the top bit. This gives \(2^n - x\).
Output: the \(n\)-bit pattern of \(-x\).
Worked example (8 bits). Represent \(-5\): Try it: −5 in 8 bits.
Check: unsigned, \(\text{FB}_{16} = 251 = 256 - 5\). ✓ And \(5 + (-5)\): \(0000\,0101 + 1111\,1011 = 1\,0000\,0000\); the ninth bit falls off, leaving \(0000\,0000\). ✓
The beauty of the scheme is that the hardware adder does not need to know whether numbers are signed: the same circuit adds unsigned and two’s-complement integers correctly, because both are just arithmetic modulo \(2^n\) with different labels.
1.9.4. Vocabulary
|
Two’s complement, overflow, signed and unsigned
An unsigned \(n\)-bit integer represents \(0\) to \(2^n - 1\). A signed \(n\)-bit integer in two’s complement represents \(-2^{n-1}\) to \(2^{n-1} - 1\); the top bit is the sign bit (1 = negative). Overflow is when the true mathematical result of an operation lies outside the representable range, so the stored result wraps around. For 32 bits the signed range is \(-2\,147\,483\,648\) to \(2\,147\,483\,647\). |
The range is lopsided — one more negative than positive — because zero takes one of the "non-negative" patterns. This is why \(-(-2^{31})\) overflows back to \(-2^{31}\), and why abs(INT_MIN) misbehaves.
1.9.5. Simulating it
Python’s integers never overflow, which makes them a good laboratory: we can simulate a 32-bit register by keeping only the low 32 bits.
def wrap_int32(x):
"""Reduce x to what a 32-bit two's-complement register would hold."""
x &= 0xFFFFFFFF # keep the low 32 bits
return x - (1 << 32) if x & 0x80000000 else x # top bit set => negative
big = 2_147_483_647 # 2^31 - 1, the largest int32
print(wrap_int32(big + 1))
print(wrap_int32(-big - 1 - 1))
print(wrap_int32(-5), hex(-5 & 0xFFFFFFFF))
Try it: Watch int32 wrap around.
-2147483648 2147483647 -5 0xfffffffb
1.9.6. Failure modes
|
Overflow is silent
Most languages do not stop when integers overflow. In C and C++ signed overflow is undefined behaviour — the compiler may assume it never happens and optimise accordingly, sometimes deleting your overflow check. Java and Go wrap silently. Rust panics in debug builds and wraps in release builds. A classic bug: the midpoint |
Try it: Why −1 < 0u is false.
|
Ones' complement and the two zeros
Early computers tried other schemes. Sign-magnitude used the top bit as a minus sign; ones' complement negated by flipping bits without adding 1. Both have two zeros (\(+0\) and \(-0\)) and need special adder logic. Two’s complement won because the plain unsigned adder just works. Floating point, interestingly, still uses sign-magnitude, which is why IEEE 754 has both |
|
Overflow clock
An \(n\)-bit clock with a slider for \(n\) from 3 to 8. Each position shows its bit pattern and both its unsigned and signed labels. Add or subtract a chosen amount and watch the hand move; the overflow boundary flashes when crossed. A second mode multiplies, showing that multiplication modulo \(2^n\) also wraps. |
1.9.7. Exercises
-
What range of values does a signed 8-bit integer hold? An unsigned 16-bit integer?
-
Find the 8-bit two’s-complement pattern for \(-1\), \(-128\), and \(-100\).
-
What signed 8-bit value does the pattern \(1001\,0110_2\) represent?
-
In 8-bit signed arithmetic, compute \(100 + 50\). What value is stored, and why?
Answers
-
Signed 8-bit: \(-2^7 = -128\) to \(2^7 - 1 = 127\). Unsigned 16-bit: 0 to \(2^{16} - 1 = 65\,535\).
-
\(-1\): invert \(0000\,0001\) to \(1111\,1110\), add 1: \(1111\,1111\). \(-128\): \(256 - 128 = 128 = 1000\,0000\). \(-100\): \(256 - 100 = 156 = 1001\,1100\).
-
Top bit is 1, so negative. Unsigned value \(128 + 16 + 4 + 2 = 150\); signed value \(150 - 256 = -106\). (Or: invert to \(0110\,1001 = 105\), add 1: 106, so the value is \(-106\).)
-
The true sum 150 exceeds 127. The stored pattern is that of 150, which read as signed is \(150 - 256 = -106\). The result wrapped around the clock.
1.10. Estimation and rounding
1.10.1. The problem
A cloud bill says a job processed 3.8 TB at $0.023 per GB. Is the $87.40 charge plausible? A colleague claims a loop over 50,000 records with a 2 ms database call each "takes a couple of seconds". Right? You do not need a calculator to answer either; you need estimation. Estimation is how you catch errors — your own, a spreadsheet’s, a program’s — before they cost you.
1.10.2. Rounding
|
Rounding, significant figures, truncation
To round a number is to replace it by a nearby number with fewer digits. Rounding "to the nearest 10", "to 2 decimal places" (2 d.p.), or "to 3 significant figures" (3 s.f.) specifies which digit is the last one kept. The standard rule: look at the first digit dropped; if it is 5 or more round up, otherwise round down. Truncation simply drops digits (always toward zero). The symbol \(\approx\) means "approximately equal to". |
Input: a number \(x\) and the place to keep (e.g. hundredths).
Steps:
-
Identify the rounding digit — the last digit to keep.
-
Look at the digit immediately to its right (the decider).
-
If the decider is 0–4, keep the rounding digit. If 5–9, increase it by 1 (carrying if it was 9).
-
Drop all digits after the rounding digit (replacing them with zeros if they are to the left of the decimal point).
Output: the rounded number.
Worked examples. \(3.14159\) to 2 d.p.: rounding digit 4, decider 1, so \(3.14\). \(2.7183\) to 1 d.p.: rounding digit 7, decider 1, so \(2.7\). \(47\,862\) to the nearest thousand: rounding digit 7, decider 8, so \(48\,000\). \(9.96\) to 1 d.p.: rounding digit 9, decider 6, so the 9 becomes 10, carry: \(10.0\) (keep the trailing zero to show the precision).
Significant figures count from the first non-zero digit: \(0.004\,072\) to 2 s.f. is \(0.0041\). They get a fuller treatment alongside scientific notation in Chapter 3.
1.10.3. Alternative rounding rules
"Round half up" is biased: over many values ending in exactly 5, it always goes up, nudging totals upward. Round half to even ("banker’s rounding") sends an exact half to whichever neighbour is even: \(2.5 \to 2\), \(3.5 \to 4\). Over many values, the ups and downs cancel. IEEE 754 floating-point uses round-half-to-even by default, and so does Python’s round:
>>> round(2.5), round(3.5), round(0.125, 2), round(2.675, 2)
(2, 4, 0.12, 2.67)
The last one is not banker’s rounding: \(2.675\) cannot be stored exactly in binary and is actually stored as a value slightly below 2.675, so it rounds down. That is a story for Chapter 2.
1.10.4. Choosing a method
-
Everyday reporting: round half up — it is what readers expect.
-
Accumulating many rounded values (financial ledgers, statistics): round half to even, or better, do not round until the end.
-
Converting to an integer index or a count of whole items: truncation or floor, deliberately.
|
Rounding too early
Round only at the end. Rounding intermediate results compounds errors: \(0.4 + 0.4 + 0.4 = 1.2\), which rounds to 1, but rounding each term first gives \(0 + 0 + 0 = 0\). Double rounding is a related trap: \(1.45\) to 1 d.p. is \(1.5\) (half up), then to the nearest whole is 2; but \(1.45\) rounded directly to the nearest whole is 1. |
1.10.5. Estimation
Estimation means replacing numbers by round values that are easy to work with, computing, and judging whether the true answer is close.
The cloud bill. \(3.8 \text{ TB} \approx 4000 \text{ GB}\) (rounding up a little). \(\$0.023 \approx \$0.02\) (rounding down a little — the errors partly cancel). \(4000 \times 0.02 = 80\). So about $80–$90: the $87.40 charge is plausible. (Exactly: \(3800 \times 0.023 = 87.40\).)
The loop. \(50\,000 \times 2 \text{ ms} = 100\,000 \text{ ms} = 100 \text{ s}\), nearly two minutes, not "a couple of seconds". The colleague is out by a factor of about 50 — the kind of error estimation is built to catch.
Order-of-magnitude (Fermi) estimates. How many piano tuners are in Chicago? Enrico Fermi famously posed such questions to students: chain together rough guesses (people, households, pianos per household, tunings per year, tunings per tuner per year), each rounded to a power of ten. Individual errors tend to partially cancel, and the result is often within a factor of 3 of the truth. Chapter 3 develops the power-of-ten thinking that makes this work.
|
Estimation trainer
The app shows a quick calculation (\(387 \times 52\), \(0.023 \times 3800\), \(7.9 \text{ GB} / 41 \text{ s}\)) for three seconds, then asks for an estimate. Score by how close the estimate is on a logarithmic scale, and track your typical error factor over time. |
1.10.6. Exercises
-
Round \(6.0451\) to (a) 2 d.p., (b) 1 d.p., (c) 3 s.f., (d) the nearest whole number.
-
Estimate \(48.7 \times 21.3\), then compute it exactly. What was your relative error?
-
A service handles 1,200 requests per second, each producing a 3 KB log line. Roughly how much log data is produced per day?
Answers
-
(a) \(6.05\) (decider 5, round up). (b) \(6.0\) (decider 4). (c) \(6.05\). (d) \(6\).
-
\(50 \times 20 = 1000\). Exactly: \(48.7 \times 21.3 = 1037.31\). Relative error \((1037.31 - 1000)/1037.31 \approx 0.036\), about 3.6%. (Rounding 48.7 up and 21.3 down partly cancelled.)
-
\(1200 \times 3 \text{ KB} = 3600 \text{ KB/s} \approx 3.6 \text{ MB/s}\). A day is \(86\,400 \approx 10^5\) seconds. \(3.6 \text{ MB} \times 10^5 \approx 3.6 \times 10^5 \text{ MB} \approx 360 \text{ GB}\) per day. (Exactly, with 86,400 s: about 311 GB.)
1.11. Interactive tools
Browser tools on the companion website that go with this chapter. Each example link in the chapter opens one of them with that example already set up.
1.12. Mastery check
-
Classify each number as natural, integer, rational, or irrational (give the smallest set it belongs to): \(-4\), \(0.75\), \(\sqrt{9}\), \(\sqrt{10}\), \(0.\overline{6}\).
-
Convert \(1101\,0110_2\) to hex and to decimal. Convert 300 to binary.
-
Compute \(49 \times 51\) mentally and name every arithmetic law you used.
-
Prove that \((-a)(-b) = ab\) starting from \((-1)(-1) = 1\) and the laws of arithmetic.
-
Evaluate \(12 - 2 \times (1 - 4)^2 \div 6\). Then state what Python prints for
-4 ** 0.5 + 10 // -3. -
Find the prime factorisation of 2024 and explain why trial division can stop where it does.
-
What is the 8-bit two’s-complement pattern of \(-37\)? What happens in 8-bit signed arithmetic if you compute \(127 + 1\)?
-
Estimate the number of seconds in a year to one significant figure, then to three.
Decision rule: All correct without hesitation → move on to Chapter 2. Stuck on 1–2 → reread the matching section (Section 1.1, Section 1.3, Section 1.4, Section 1.5, Section 1.6, Section 1.8, Section 1.9, Section 1.10). Stuck on more → work the section exercises first.
Mastery check answers
-
\(-4\): integer. \(0.75 = \tfrac{3}{4}\): rational. \(\sqrt{9} = 3\): natural. \(\sqrt{10}\): irrational (10 is not a perfect square; the argument for \(\sqrt{2}\) adapts). \(0.\overline{6} = \tfrac{2}{3}\): rational.
-
Group bits: \(1101 = \text{D}\), \(0110 = 6\), so \(\text{D6}_{16}\). Decimal: \(13 \times 16 + 6 = 214\). For 300: \(256\) fits (44 left), 128 no, 64 no, 32 fits (12 left), 16 no, 8 fits (4 left), 4 fits (0 left), 2 no, 1 no: \(1\,0010\,1100_2\). Check: \(256 + 32 + 8 + 4 = 300\). ✓
-
\(49 \times 51 = 49 \times (50 + 1) = 49 \times 50 + 49\) (distributive) \(= 2450 + 49 = 2499\). Alternatively \((50 - 1)(50 + 1) = 2500 - 1 = 2499\) (distributive twice, commutative, and inverse to cancel \(-50 + 50\)).
-
\((-a)(-b) = ((-1)a)((-1)b)\) (since \(-x = (-1)x\)) \(= (-1)(-1)\,ab\) (commutative and associative laws to regroup) \(= 1 \cdot ab = ab\) (identity).
-
Brackets: \(1 - 4 = -3\); exponent: \((-3)^2 = 9\); then \(2 \times 9 = 18\), \(18 \div 6 = 3\); finally \(12 - 3 = 9\). Python:
-4 ** 0.5is \(-(4^{0.5}) = -2.0\);10 // -3floors \(-3.33\ldots\) to \(-4\); the sum is-6.0. -
\(2024 = 2 \cdot 1012 = 2^2 \cdot 506 = 2^3 \cdot 253\); 253 is not divisible by 3, 5, or 7; \(253 = 11 \times 23\). So \(2024 = 2^3 \cdot 11 \cdot 23\). After dividing out 11 the remainder is 23, and the next trial divisor 12 has \(12^2 = 144 > 23\), so 23 must be prime: a composite number always has a factor no larger than its square root.
-
\(37 = 0010\,0101\); invert: \(1101\,1010\); add 1: \(1101\,1011\) (\(= \text{DB}_{16} = 219 = 256 - 37\)). \(127 + 1\) overflows: the pattern \(1000\,0000\) is read as \(-128\).
-
\(365 \times 24 \times 3600\). Roughly \(400 \times 25 \times 4000 = 4 \times 10^7\) is a little high (all three rounded up); more carefully \(365 \times 86\,400 = 31\,536\,000 \approx 3 \times 10^7\) (1 s.f.) or \(3.15 \times 10^7\) (3 s.f.). A handy fact: a year is about \(\pi \times 10^7\) seconds.