Chapter 11: Discrete Math 1
Discrete mathematics is the mathematics of distinct, separated structures, as opposed to the continuous structures of calculus. Its central activity is proof: constructing airtight logical arguments. Every concept in it appears directly in computer science. Sets become data structures, logic becomes boolean algebra and type systems, induction becomes recursive correctness arguments, relations become database schemas, and functions become the foundation of programming. Counting, meanwhile, is how you size anything: a model’s parameters, the FLOPs of a forward pass, the bytes of a cache.
Concepts from other sections (15)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Loop invariant: a statement that holds before a loop, survives each iteration, and with the exit condition implies the result. Read more: 11.3.4 Relations, functions, and validation
- Injective: no two inputs share an output; for a dict, no value appears twice. Read more: 11.2 Injective, surjective, bijective: the GPT-2 byte map
- Bijective: both injective and surjective; exactly the functions that have an inverse. Read more: 11.2 Injective, surjective, bijective: the GPT-2 byte map
- Product rule / quotient rule: and , the rules for differentiating a product or a ratio of two functions. Read more: Chapter 7: Calculus 1
- Equivalence relation: a reflexive, symmetric, transitive relation; its classes partition the set. Read more: 11.3.4 Relations, functions, and validation
- Bijection: a function that is both injective and surjective, and so has an inverse. Read more: 11.3.4 Relations, functions, and validation
- GQA / MLA: attention variants that shrink the KV cache by sharing K/V heads across groups of query heads, or by compressing K/V into a low-rank latent. Read more: 5.3 Model landscape and lifecycle in AI Engineering
- Mixture of experts (MoE): a layer of many expert MLPs of which a router picks per token. Read more: 13.8 Mixture of Experts in AI Engineering
- FLOPs per token: for the matmul parameters touched plus the parameter-free attention term; three times that for a training step. Read more: 11.1 Counting: parameters, FLOPs, KV bytes, and memory plans
- Byte-level: the base alphabet is the 256 bytes (through the byte map), so every text encodes and there is no unknown token. Read more: 7.2 Byte-level BPE in AI Engineering
- Base case: an input on which a recursive function returns directly without calling itself; together with an input that strictly shrinks on every call, it guarantees that the recursion terminates. Read more: Chapter 13: Recursion and divide-and-conquer in Programming and Algorithms
- One-to-one: different inputs always give different outputs; exactly the functions with an inverse. Read more: 6.5 Problem set: functions, logarithms, trigonometry, series, polynomials, and inequalities
- Union-find / disjoint-set union (DSU): a forest that keeps elements in disjoint sets, with
findreturning a set’s root andunionmerging two sets; it answers “are these connected?” as edges arrive in nearly constant amortized time per operation. Read more: Chapter 8: Graphs in Programming and Algorithms - Expected value: the average outcome across many repetitions of a situation under the model. Read more: Chapter 4: Uncertainty and evidence
- Divide and conquer / divide-and-conquer: an algorithm design that splits a problem into independent subproblems, solves them recursively, and combines their results; unlike dynamic programming the subproblems do not overlap, and the gain comes from better asymptotics, as in merge sort. Read more: Chapter 13: Recursion and divide-and-conquer in Programming and Algorithms
This chapter starts where the rest of the book needs it most. Its problem set builds the vocabulary and the proof habits that later chapters assume: sets and logic, counting, the standard proof methods, induction and loop invariants, relations, and functions. Its two build sections then put two of those ideas to work. The first counts a transformer’s parameters, FLOPs, KV-cache bytes, and training memory exactly, from a handful of config integers. The second uses injective, surjective, and bijective to derive the byte-to-character map that every GPT-2 style tokenizer depends on. The survey after the section list covers the wider territory of a first discrete math course, following Hammack’s Book of Proof, with a worked example for each topic.
Learning objectives
- Read and write rigorous proofs: direct, contrapositive, contradiction, cases, and induction, including loop invariants.
- Use the language of sets, logic, and quantifiers, including negating nested quantifiers.
- Count with the product rule, permutations, combinations, and stars and bars, and apply them to parameter, FLOP, and KV-cache counts.
- Classify relations, and recognize equivalence relations as partitions.
- Prove functions injective, surjective, or bijective, and explain why only bijections have inverses.
Before you begin
Section titled “Before you begin”The chapter needs no earlier mathematics beyond high-school algebra. For the counting section, powers of ten and logarithms from Exponents, logarithms, and units of information help with reading counts like . The problem set comes last in the list below by file order, but it is designed to be worked first.
In this chapter
Section titled “In this chapter”- Counting: parameters, FLOPs, KV bytes, and memory plans: counts a decoder’s parameters per component so they match Hugging Face exactly for dense, GQA, MoE, and MLA models, and derives KV-cache bytes, FLOPs per token, and a training memory plan, all as exact integers.
- Injective, surjective, bijective: the GPT-2 byte map: builds the three definitions as checks on a dict, and derives GPT-2’s bijection from the 256 bytes to 256 visible characters that byte-level BPE vocabularies are written in.
- Discrete math 1 problem set: problems with worked answers and model proofs on sets and logic, counting, proof techniques, induction and loop invariants, relations, and functions and bijections. Work it before the two sections above.
A survey of the subject
Section titled “A survey of the subject”The sections above focus on the parts of discrete math that code depends on. The rest of this opening surveys a first course in the subject, following Hammack’s Book of Proof. Each topic gives the key definitions and theorems, worked examples, and the textbook exercises to practice on.
Book of Proof chapter 1, sections 1.1 to 1.8. A set is an unordered collection of distinct elements, described by listing, , or in set-builder notation, . is a subset of if every element of is in . The power set is the set of all subsets of . The union is , the intersection is , and the complement is . The Cartesian product is , with .
Three results recur. De Morgan’s laws, and , say that “not (this or that)” is “not this and not that”: negation swaps union and intersection. Inclusion-exclusion for two sets, , corrects the double count of the overlap. And , because each element is independently in or out.
For example, prove . Let . Then and . If , then , so is in the right side. If , then , so again is in the right side. The reverse inclusion is similar.
Practice: Hammack chapter 1 exercises 1 to 8, 13 to 18, and 25 to 30; for a challenge, 31 to 36.
Book of Proof chapter 2, sections 2.1 to 2.10. A proposition is a statement that is either true or false. is true only when both are; when at least one is; reverses the truth value. The conditional is false only when is true and is false, and the biconditional is true when and have the same truth value. A predicate is a statement with a variable, such as = ” is even”. The universal quantifier asserts for every in the domain; the existential quantifier asserts it for at least one.
is equivalent to : “if then ” fails only when is true and is false. It is also equivalent to its contrapositive : “if it rained then the ground is wet” is the same as “if the ground is dry then it didn’t rain.” And negation swaps quantifiers, and , just as De Morgan’s laws swap AND and OR.
For example, negate “for every there exists such that implies .” The negation is “there exists such that for all there exists with and .” Each quantifier flips, and the implication becomes a conjunction with the consequent negated.
Practice: Hammack chapter 2 exercises 1 to 10 and 15 to 22; for a challenge, 23 to 28.
Counting
Section titled “Counting”Book of Proof chapter 3, sections 3.1 to 3.5. The multiplication principle: if task 1 has outcomes and task 2 has , the sequence has . The addition principle: if the tasks are mutually exclusive, the total is . A permutation is an ordered arrangement, ; a combination is an unordered selection, , read ” choose ”.
The binomial theorem is : expanding , each term chooses from some factors and from the rest, and there are ways to choose the factors for . Pascal’s identity, , says that to choose items from , you either include item (then choose from the remaining ) or exclude it (choose from ). Stars and bars: the number of ways to distribute identical objects into distinct bins is , the arrangements of stars and dividers in a row.
Two examples. How many 5-card poker hands contain exactly 2 aces? Choose 2 aces from 4, , and the remaining 3 cards from the 48 non-aces, , for . How many bit strings of length 8 have exactly 3 ones? Choose the positions of the ones: .
Practice: Hammack chapter 3 exercises 1 to 12 and 17 to 24; for a challenge, 25 to 30.
Direct proof
Section titled “Direct proof”Book of Proof chapter 4, sections 4.1 to 4.5. A direct proof of assumes and uses definitions, theorems, and logical reasoning to conclude . The technique is always the same: assume the hypothesis, unpack the definitions, manipulate using known results, and arrive at the conclusion.
Prove that if is odd, then is odd. Assume is odd, so for some integer . Then . Since is an integer, has the form , so it is odd.
Prove that if and , then . Since , for some integer ; since , for some integer . Then , and since is an integer, .
Practice: Hammack chapter 4 exercises 1 to 8, 13 to 18, and 23 to 28; for a challenge, 29 to 34.
Contrapositive proof
Section titled “Contrapositive proof”Book of Proof chapter 5, sections 5.1 to 5.3. A contrapositive proof of proves the logically equivalent instead. Use it when the negation of gives you more to work with than assuming directly.
Prove that if is even, then is even. The contrapositive is: if is odd, then is odd. Assume ; then , which is odd. This avoids the difficulty of working directly from ” is even.”
Prove that if is odd, then is even. The contrapositive: if is odd, , then , which is even.
Practice: Hammack chapter 5 exercises 1 to 8 and 11 to 16; for a challenge, 17 to 20.
Proof by contradiction
Section titled “Proof by contradiction”Book of Proof chapter 6, sections 6.1 to 6.4. A proof by contradiction assumes the statement is false and derives a logical contradiction: reason until you reach an impossibility (a number that is both even and odd, or a rational that is irrational), and conclude that the original statement must be true.
Prove that is irrational. Assume in lowest terms, . Then , so . Thus is even, so is even (by the contrapositive proof above). Write . Then , so , and is even. But then both and are even, contradicting .
Prove that there are infinitely many primes. Assume there are finitely many, , and consider . is not divisible by any (the remainder is 1), so is either prime itself or has a prime factor not in the list. Either way, the list was not complete: a contradiction.
Practice: Hammack chapter 6 exercises 1 to 8 and 13 to 18; for a challenge, 19 to 24.
Non-conditional proofs
Section titled “Non-conditional proofs”Book of Proof chapter 7, sections 7.1 to 7.4. Some statements are not a single implication. An if-and-only-if proof proves both directions, and . An existence proof shows that an object with the desired property exists, constructively or not. A uniqueness proof shows at most one object has the property: assume two, and show they are equal. A proof by cases breaks the claim into exhaustive cases and proves each separately.
Prove that is odd if and only if is odd. () If , then is odd. () By contrapositive: if , then is even. Both directions are established.
Practice: Hammack chapter 7 exercises 1 to 8, 13 to 18, and 25 to 30; for a challenge, 31 to 36.
Mathematical induction
Section titled “Mathematical induction”Book of Proof chapter 10, sections 10.1 to 10.4. Weak induction proves , then assumes and proves , and concludes for all . Strong induction assumes for all and proves . Structural induction inducts on recursively defined structures such as trees, lists, and formulas. Underneath all three is the well-ordering principle: every nonempty subset of the natural numbers has a least element. It is logically equivalent to induction: if induction failed, there would be a smallest counterexample, contradicting well-ordering.
Prove . Base case : the left side is 1 and the right side is . Inductive step: assume . Then , the formula with .
Prove for all , in strong induction style. Base: . Assume for all . Then , since .
By structural induction, every binary tree with internal nodes has leaves. Base: a tree with 0 internal nodes has 1 leaf. Inductive step: a tree with a root has a left subtree ( internal nodes, leaves) and a right subtree ( internal, leaves). Its internal nodes total , and its leaves , which is the internal count plus 1.
Practice: Hammack chapter 10 exercises 1 to 10, 15 to 22, and 27 to 32; for a challenge, 33 to 38.
Relations
Section titled “Relations”Book of Proof chapter 11, sections 11.1 to 11.6. A relation on is a subset of ; write for . It is reflexive if for all , symmetric if implies , and transitive if and imply . An equivalence relation has all three properties, and the equivalence class of is . A partition is a collection of nonempty, pairwise disjoint subsets whose union is . A partial order is reflexive, antisymmetric ( and imply ), and transitive.
The fundamental theorem of equivalence relations says the equivalence classes of an equivalence relation on form a partition of , and conversely every partition defines an equivalence relation. They are the same concept viewed from two angles: “being equivalent” means “being in the same part.”
For example, on define if and only if , congruence mod 3. It is reflexive, since ; symmetric, since implies ; and transitive, since and imply . Its classes are , , and , which partition .
Practice: Hammack chapter 11 exercises 1 to 10 and 15 to 22; for a challenge, 23 to 28.
Functions
Section titled “Functions”Book of Proof chapter 12, sections 12.1 to 12.6. A function from to is a relation in which every element of is related to exactly one element of . It is an injection (one-to-one) if implies , a surjection (onto) if every has some with , and a bijection if both, a one-to-one correspondence. Composition is , and the inverse exists if and only if is a bijection, with .
Four theorems organize the topic. Composition preserves the properties: if and are injective, so is , and likewise for surjective; composing two “no-collision” maps gives a “no-collision” map, and composing two “everything is hit” maps gives an “everything is hit” map. has an inverse if and only if it is a bijection: to undo a function, every output must come from exactly one input. Cantor’s theorem, for any set (there is no surjection from onto its power set), says there are always more subsets than elements, which is the source of different sizes of infinity. Schröder-Bernstein: if there are injections and , there is a bijection between them; if each set fits inside the other, they are the same size.
Two examples. , , is injective but not surjective. If then ; but requires , so 4 has no preimage. And , , is a bijection: if then (the cube root is well defined on ), and for any , satisfies . Its inverse is .
Practice: Hammack chapter 12 exercises 1 to 10, 15 to 22, and 27 to 34; for a challenge, 35 to 40.
Choosing a technique
Section titled “Choosing a technique”Much of the skill in the subject is recognizing which method fits a claim. This table pairs each with when to reach for it:
| Technique | When to use | Key formula or idea |
|---|---|---|
| Direct proof | prove when definitions lead forward | assume , derive |
| Contrapositive | is hard; is easier | negate both, reverse the direction |
| Contradiction | existence, uniqueness, or irrationality proofs | assume the negation, derive an impossibility |
| Weak induction | prove for all base | base case, plus |
| Strong induction | depends on several prior cases | base case, plus (all for ) |
| Structural induction | properties of recursive structures (trees, lists) | base structure, plus induction on construction |
| Proof by cases | the domain splits naturally | prove each case; make sure the cases are exhaustive |
| Counting (multiplication) | sequential independent choices | multiply the options at each stage |
| Counting (combinations) | unordered selections | |
| Bijective proof | show two counts are equal | find a one-to-one correspondence |
Key terms
Section titled “Key terms”- Power set: the set of all subsets of ; it has elements because each element is independently in or out of a subset.
- Cartesian product: , the set of all ordered pairs, with ; relations and functions are subsets of it.
- De Morgan’s laws: and , and likewise ; negation swaps union with intersection and OR with AND.
- Universal quantifier / existential quantifier: asserts for every in the domain, and for at least one; negating a statement flips each quantifier, .
- Multiplication principle: if one task has outcomes and a second has for each of them, the sequence has outcomes; with the addition principle for mutually exclusive cases, it is the basis of all counting.
- Binomial theorem: , because each term picks from of the factors, which can be done in ways.
- Stars and bars: the number of ways to distribute identical objects into distinct bins is , counted as arrangements of stars and dividers in a row.
- Direct proof: a proof of that assumes , unpacks the definitions, and reasons forward with known results until it reaches .
- Proof by contradiction: a proof that assumes the statement is false and derives an impossibility, so the statement must be true; it is the standard route to results such as the irrationality of .
- Strong induction: induction in which the step assumes for every from the base case up to , not just , before proving ; it fits claims where a case depends on several earlier ones.
- Structural induction: induction over a recursively defined structure such as a list, tree, or formula: prove the property for the base structures, then show that each construction rule preserves it.
- Well-ordering principle: every nonempty set of natural numbers has a least element; it is logically equivalent to induction, since a failed induction would have a smallest counterexample.
- Equivalence class: for an equivalence relation on , the set of everything equivalent to ; the classes partition , and every partition defines an equivalence relation.
- Partial order: a relation that is reflexive, antisymmetric ( and imply ), and transitive, such as or “is a subset of”; some pairs may be incomparable, which is why dependency graphs need a topological sort.
- Cantor’s theorem: for every set , because no function from onto its power set exists; it shows there are different sizes of infinity.
- Schröder-Bernstein theorem: if there are injections and , there is a bijection between and ; if each set fits inside the other, they have the same size.
Where this leads
Section titled “Where this leads”These ideas surface throughout computing. Propositional logic is boolean algebra, circuit design, and SAT solving; quantifiers and predicates are the WHERE clauses of database queries. Induction proves recursive algorithms correct, and loop invariants prove iterative ones, as in Graphs, DAGs, and an iterative topological sort. Sets underlie data structures such as hash sets and tree sets, and type systems. Equivalence relations underlie union-find and database normalization, and partial orders underlie topological sort and dependency resolution. Bijections are the basis of encoding and decoding, hashing, and encryption, and Modular arithmetic, hashing, and PCG32 continues in that direction. Counting and combinatorics drive algorithm analysis, from average cases and expected values in Probability and statistics to the binomial sums in divide-and-conquer recurrences.
Further reading
Section titled “Further reading”- Richard Hammack, Book of Proof (CC BY-ND), the textbook this chapter follows. Write your proofs by hand in complete sentences and compare them with Hammack’s solutions for style and rigor.