Chapter 12: Discrete Math 2
This chapter covers the discrete structures that turn up most directly in algorithms and systems: graphs, number theory, and advanced counting. Graph theory is the language of networks, dependencies, and state machines, and it is the single most widely used discrete structure in computer science. Number theory underpins cryptography, hashing, and random number generation. Recurrence relations are the bridge between recursive algorithms and closed-form running times. Together these topics form the mathematical core of a computer science education.
Concepts from other sections (25)
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.
- Directed graph: a set of vertices and a set of ordered pairs of vertices called edges. Read more: 12.1 Graphs, DAGs, and an iterative topological sort
- Topological order: a list of the vertices in which every edge points from an earlier vertex to a later one. Read more: 12.1 Graphs, DAGs, and an iterative topological sort
- Depth-first search (DFS): traversal that follows one path as far as possible before backtracking, using a stack. Read more: 18.6 Graph as an adjacency list in Programming and Algorithms
- Trie: a rooted tree whose edges carry characters so that each node spells the string on its path. Read more: 12.2 Trees and tries, longest-prefix match
- PCG32: an LCG whose output is a permutation (xorshift, then a state-chosen rotation) of the old state. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python
- FNV-1a: a byte hash that xors each byte in and then multiplies by a fixed prime mod . Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python
- DAG: a directed graph with no directed cycle. Read more: 12.1 Graphs, DAGs, and an iterative topological sort
- MinHash: estimating Jaccard similarity by how often the minima of random permutations agree. Read more: 12.5 Discrete math 2 problem set, part b: trees, birthday bounds, MinHash and LSH, Bloom filters, recurrences
- Bloom filter: a bit array with hashes per key that never misses an inserted key and has a tunable false-positive rate. Read more: 12.5 Discrete math 2 problem set, part b: trees, birthday bounds, MinHash and LSH, Bloom filters, recurrences
- 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
- Birthday bound: the observation that keys in buckets start to collide at . Read more: 12.5 Discrete math 2 problem set, part b: trees, birthday bounds, MinHash and LSH, Bloom filters, recurrences
- Inclusion-exclusion: counting a union by alternately adding and subtracting the sizes of intersections. Read more: 12.5 Discrete math 2 problem set, part b: trees, birthday bounds, MinHash and LSH, Bloom filters, recurrences
- Bijection: a function that is both injective and surjective, and so has an inverse. Read more: 11.3.4 Relations, functions, and validation
- Post-order: the order in which a depth-first search finishes vertices. Read more: 12.1 Graphs, DAGs, and an iterative topological sort
- Longest-prefix match: finding the longest key that is a prefix of the text at a given position. Read more: 12.2 Trees and tries, longest-prefix match
- SplitMix64: the mixer used to derive child seeds that depend only on the seed and the purpose. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python
- Euler’s formula: ; multiplying by it rotates by . Read more: 6.2 Trigonometry, rotations, complex numbers, and Euler’s formula
- Power series: a series in powers of ; it converges for less than its radius of convergence and can diverge beyond it. Read more: Chapter 8: Calculus 2
- Ordinary differential equation (ODE): an equation relating a function of one variable to its derivatives, such as ; it models how a system changes, and gradient descent is Euler’s method applied to one. Read more: Chapter 8: Calculus 2
- Geometric sequence: a sequence that multiplies by the same ratio at every step, . Read more: 6.3 Sequences, geometric series, and frequency ladders
- Fixed point: a value with . Read more: 15.5 Fixed-point iteration and fast inverse square root in C
- Breadth-first search (BFS): traversal in order of hop distance using a FIFO queue. Read more: 18.6 Graph as an adjacency list in Programming and Algorithms
- Repeated squaring: computing with O(log n) multiplications by following the binary digits of . Read more: 19.3 Compile-time matrix in Programming and Algorithms
- Pigeonhole principle: inputs cannot produce more than distinct outputs, so for equal sizes injective and surjective coincide. Read more: 11.2 Injective, surjective, bijective: the GPT-2 byte map
- Binary search tree (BST): a binary tree in which every node’s value is greater than every value in its left subtree and less than every value in its right subtree, so a search follows one root-to-leaf path and an in-order traversal yields the values in sorted order. Read more: Chapter 7: Trees in Programming and Algorithms
The chapter moves from structure to arithmetic to probability. It opens with directed graphs and the topological order that every backward pass in an autograd engine depends on, built as an iterative depth-first search. Trees and tries follow, the structure behind every tokenizer’s “which vocabulary entries start here?” question. Then modular arithmetic becomes concrete in PCG32, the random generator the rest of the books draw from, and in the FNV-1a and universal hash functions. Two problem sets close the chapter: the first drills DAGs, modular arithmetic, and hashing by hand; the second derives the numbers you must choose for tries, hash tables, MinHash and LSH, Bloom filters, and divide-and-conquer recurrences.
Learning objectives
- Define graphs, DAGs, trees, and tries, prove their basic counting facts, and implement an iterative topological sort and a trie.
- Work fluently in and on fixed-width machine words, and explain why PCG32, FNV-1a, and universal hashing are built the way they are.
- Predict collision rates with birthday bounds, size a Bloom filter, and read an LSH S-curve.
- Solve linear recurrences and divide-and-conquer recurrences, and use inclusion-exclusion and combinatorial proofs.
Before you begin
Section titled “Before you begin”You need the sets, relations, counting, induction, and bijections of Discrete Math 1, and its problem set is good preparation for the proofs here. The companion textbook is Discrete Mathematics: An Open Introduction by Oscar Levin (https://discrete.openmathbooks.org, CC BY-SA 4.0). Levin’s text is conversational and example-rich; draw every graph by hand, and check any counting formula on small cases before trusting it.
In this chapter
Section titled “In this chapter”- Graphs, DAGs, and an iterative topological sort proves that a topological order exists exactly for DAGs and builds
toposort, the reverse depth-first post-order that autograd’s backward pass walks, iterative and keyed by identity. - Trees and tries, longest-prefix match counts the nodes of a trie and builds longest-prefix match, the lookup behind WordPiece, the Unigram lattice, and added-token matching.
- Modular arithmetic, hashing, and PCG32 in Python derives PCG32 from a linear congruential generator, with bit-exact uniforms, unbiased bounded integers, SplitMix64 sub-streams, FNV-1a, and universal hashing.
- Discrete math 2 problem set, part a: DAGs, modular arithmetic, hashing works topological orders, machine-word arithmetic, and hash-table load by hand, including the correctness proof of the iterative DFS.
- Discrete math 2 problem set, part b: trees, birthday bounds, MinHash and LSH, Bloom filters, recurrences derives the formulas that set the parameters of tries, hash tables, near-duplicate detection, Bloom filters, and recursive algorithms.
The mathematics at a glance
Section titled “The mathematics at a glance”The sections above apply the theory to specific code. This survey collects the classical definitions and theorems of the chapter in one place, following Levin, so you can see the whole field the sections draw on.
Graph theory
Section titled “Graph theory”A graph is , a set of vertices and a set of edges (pairs of vertices). The degree is the number of edges incident to . A path is a sequence of distinct vertices in which consecutive vertices are adjacent, and a cycle is a path that starts and ends at the same vertex. A graph is connected when there is a path between every pair of vertices. An isomorphism is a bijection that preserves adjacency. A planar graph can be drawn in the plane without edge crossings. The chromatic number is the minimum number of colours needed so that no two adjacent vertices share a colour. An Euler path uses every edge exactly once (an Euler circuit is a closed one); a Hamilton path visits every vertex exactly once (a Hamilton circuit is a closed one). A tree is a connected acyclic graph, and a bipartite graph is one whose vertices split into two sets so that every edge goes between the sets. Levin covers all of this in chapter 4, sections 4.1 to 4.7.
The key theorems each have a short intuition:
- Handshaking lemma. The sum of all degrees is , because each edge contributes 1 to the degree of each endpoint and so is counted twice.
- Euler’s formula for planar graphs. A connected planar graph has , where is the number of faces. This topological invariant constrains planar graphs; its corollary shows that and are not planar.
- Euler path and circuit criterion. A connected graph has an Euler circuit if and only if every vertex has even degree, and an Euler path (not a circuit) if and only if exactly two vertices have odd degree. To traverse every edge, you must be able to leave every vertex as many times as you enter it.
- Tree characterizations. For a graph on vertices the following are equivalent: is a tree; is connected with edges; is acyclic with edges; there is a unique path between any two vertices. Trees are minimally connected: removing any edge disconnects them.
- Four colour theorem. Every planar graph can be properly coloured with at most 4 colours, so any map can be coloured with 4 colours without adjacent regions sharing one. The proof requires computer verification.
- Five colour theorem. Every planar graph can be properly coloured with 5 colours. This one is provable without a computer: Euler’s formula gives a vertex of degree at most 5, and induction does the rest.
Three worked examples show the theorems in use. Does , the complete graph on 4 vertices, have an Euler circuit? Every vertex has degree 3, which is odd, so no Euler circuit exists; and since more than two vertices (all four) have odd degree, there is no Euler path either.
Is planar? and , and passes. But is bipartite, so it has no triangles, which gives the stricter bound . It passes with equality, so the formula alone does not rule it out, and in fact is planar (draw it).
Finally, prove that every tree with vertices has at least two leaves (vertices of degree 1). A tree has edges, so the sum of degrees is . If at most one vertex had degree 1, the remaining vertices would have degree at least 2, giving a sum of at least , a contradiction.
Number theory
Section titled “Number theory”Number theory supplies the arithmetic. , read ” divides ”, means for some integer . The greatest common divisor is the largest with and . is congruent to modulo when , and modular arithmetic is arithmetic in with operations taken mod . A multiplicative inverse exists if and only if . Levin treats this in supplementary material; Hammack’s Book of Proof, chapters 1 to 7, applies proof technique to number theory.
The key theorems:
- Division algorithm. For any integers and there are unique and with and : every integer lands in a unique “box” relative to .
- Euclidean algorithm. , terminating when the remainder is 0. The GCD does not change when you subtract one number from the other, so taking the remainder does many subtractions at once.
- Bezout’s identity. for some integers , found by the extended Euclidean algorithm: the GCD can always be built as a linear combination of and .
- Fermat’s little theorem. If is prime and , then : with a prime modulus, exponentiation is cyclic with period dividing .
- RSA. Choose primes . Let and . Choose with and compute . The public key is and the private key is . Encrypt with and decrypt with . Euler’s theorem guarantees , so encryption and decryption are inverses.
As a worked example, compute with the Euclidean algorithm: , , , so . The extended version works backwards: , so .
To compute , use Fermat’s little theorem: , and , so .
Advanced counting
Section titled “Advanced counting”The counting tools extend those of the previous chapter. The inclusion-exclusion principle is : alternately add and subtract to correct for overcounting. The pigeonhole principle says that if objects go into boxes, some box holds at least 2; more generally, if more than objects go into boxes, some box holds at least . A recurrence relation defines in terms of earlier terms, as in . For the characteristic equation is , and its roots give the closed form. A generating function encodes a sequence as a power series. Levin covers these in chapter 1, sections 1.1 to 1.7, and chapter 2, sections 2.1 to 2.4.
The key results:
- Solving linear recurrences. If has distinct roots , then , with constants from the initial conditions; with a repeated root , . The recurrence behaves like a linear ODE, and its solution is a combination of geometric sequences.
- Master theorem. For , compare with . If grows slower, ; if they match, ; if grows faster, . The recursion tree spends most of its work at the leaves, evenly across levels, or at the root.
- Derangements. The number of permutations with no fixed point is , approximately . By inclusion-exclusion, subtract the permutations fixing at least one element, add back those fixing at least two, and so on.
Three worked examples. Solve with , : the characteristic equation has roots 2 and 3, so . From , ; from , . Solving gives and , so .
How many integers from 1 to 1000 are divisible by 2, 3, or 5? , , , , , , and . By inclusion-exclusion, .
And by pigeonhole, in any group of 13 people at least two share a birth month: 13 people, 12 months.
Combinatorial proofs
Section titled “Combinatorial proofs”The last technique replaces algebra with counting. A combinatorial proof proves an identity by showing that both sides count the same set in two different ways; double counting is the general principle that two ways of counting the same quantity yield an equality. The method is to identify a set that one side counts, then find a different way to count that yields the other side. No algebraic manipulation is needed. Levin covers this in chapter 2, sections 2.1 and 2.2, with supplementary material from Hammack.
Three classical identities fall out this way:
- Vandermonde’s identity. . Choose people from a group of men and women: the left side counts directly, and the right side splits by choosing men and women.
- Hockey stick identity. . To choose elements from , let the largest chosen element be (where ), then choose the remaining from , giving . Summing over from to gives the left side.
- Row sums of Pascal’s triangle. . The left side counts the subsets of an -element set by size; the right side counts all subsets directly, with 2 choices per element.
Two more worked examples. To prove : counts the ways to choose items from , and for each such choice the unchosen items form a set of size . That is a bijection between -element and -element subsets, so the counts agree. To prove : the left side chooses 2 people from , with in group A and in group B. The right side splits the choice into both from A (), both from B (), or one from each (), for a total of .
Techniques and where they apply
Section titled “Techniques and where they apply”The table pairs each technique with when to reach for it.
| Technique | When to use | Key formula or idea |
|---|---|---|
| BFS/DFS on graphs | explore connectivity, find paths | systematic vertex traversal |
| Euler’s formula | analyse planar graphs | |
| Degree-based arguments | prove existence of certain vertices | handshaking: sum of degrees |
| Euclidean algorithm | compute a GCD efficiently | |
| Modular exponentiation | compute efficiently | repeated squaring |
| Characteristic equation | solve linear recurrences | factor |
| Generating functions | solve counting problems and recurrences | encode a sequence as a power series |
| Inclusion-exclusion | count a union of overlapping sets | alternately add and subtract intersections |
| Pigeonhole principle | prove existence of collisions or repeats | more items than containers |
| Combinatorial proof | prove identities without algebra | count the same set two ways |
These ideas reach far into computing. Graph traversal gives shortest paths, cycle detection, and topological sort; graph colouring drives register allocation in compilers and scheduling; planar graphs appear in VLSI circuit layout and map rendering. Trees are the data structures (binary search trees, heaps, tries) and the spanning trees of networks. Euler and Hamilton paths show up in network routing and in DNA sequencing by Eulerian assembly. Modular arithmetic is the basis of hashing, checksums, and random number generators, and RSA and number theory underpin public-key cryptography and digital signatures. Recurrences give the running times of merge sort and quicksort, the master theorem classifies divide-and-conquer algorithms at a glance, and generating functions power Knuth-style analysis of algorithms. Many of these are developed in Algorithms and Systems Engineering.
Key terms
Section titled “Key terms”- Connected graph: a graph with a path (a sequence of distinct vertices, each joined to the next by an edge) between every pair of vertices; a tree is a connected graph with no cycles.
- Graph isomorphism: a bijection between the vertex sets of two graphs that preserves adjacency; isomorphic graphs are the same graph drawn or labelled differently.
- Planar graph: a graph that can be drawn in the plane with no edges crossing; connected planar graphs satisfy Euler’s formula , which bounds their edges by .
- Chromatic number: , the fewest colours needed to colour the vertices of so that no two adjacent vertices share a colour; it models register allocation and scheduling, and it is at most 4 for planar graphs.
- Euler path / Euler circuit: a walk that uses every edge exactly once, closed for a circuit; a connected graph has an Euler circuit exactly when every vertex has even degree, and an Euler path exactly when zero or two vertices have odd degree.
- Hamilton path / Hamilton circuit: a path that visits every vertex exactly once, closed for a circuit; unlike Euler paths, no simple degree test decides whether one exists.
- Bipartite graph: a graph whose vertices split into two sets with every edge running between the sets; it has no odd cycles, so in particular no triangles.
- Handshaking lemma: the degrees of a graph’s vertices sum to , because each edge adds 1 to the degree of each endpoint; it follows that the number of odd-degree vertices is even.
- Greatest common divisor (GCD): , the largest integer dividing both and ; has a multiplicative inverse modulo exactly when .
- Euclidean algorithm / extended Euclidean algorithm: computes by repeating until the remainder is 0; the extended version also returns with , which gives modular inverses.
- Bezout’s identity: for any integers and there are integers and with ; the extended Euclidean algorithm finds them.
- Fermat’s little theorem: if is prime and does not divide , then ; it reduces large exponents modulo and underlies primality tests and RSA.
- RSA: a public-key cryptosystem with modulus for primes , public exponent , and private exponent ; encryption is and decryption , and its security rests on the difficulty of factoring .
- Characteristic equation (recurrences): for a linear recurrence , the equation ; with distinct roots the closed form is .
- Generating function: the power series whose coefficients are a sequence; algebra on solves counting problems and recurrences.
- Master theorem: for divide-and-conquer recurrences , comparing with gives as , , or , depending on whether the leaves, every level, or the root dominates.
- Combinatorial proof / double counting: proving an identity by showing that both sides count the same set in two different ways, with no algebra; Vandermonde’s identity and are classic examples.
Further reading
Section titled “Further reading”- Oscar Levin, Discrete Mathematics: An Open Introduction (https://discrete.openmathbooks.org). Essential exercises: chapter 4, exercises 4.1.1 to 4.1.8, 4.2.1 to 4.2.6, 4.3.1 to 4.3.8, and 4.4.1 to 4.4.5 (graphs); chapter 1, exercises 1.1.1 to 1.1.8, 1.2.1 to 1.2.6, 1.3.1 to 1.3.8, and 1.4.1 to 1.4.8; chapter 2, exercises 2.4.1 to 2.4.8 (counting and recurrences). Challenge exercises: 4.7.1 to 4.7.6, 1.7.1 to 1.7.6, 2.4.9 to 2.4.14, and the combinatorial proofs 2.1.6 to 2.1.12.
- Richard Hammack, Book of Proof: chapters 4 to 7 review exercises, and exercises 1 to 8 of the number-theory material in chapters 4 to 6, with chapter 6’s advanced exercises as a challenge.
- As a challenge project, implement RSA by hand for small primes, such as and .