Skip to content

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.

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 Zn\mathbb{Z}_n 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.

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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 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.

A graph is G=(V,E)G = (V, E), a set of vertices VV and a set of edges EE (pairs of vertices). The degree deg⁡(v)\deg(v) is the number of edges incident to vv. 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 f:V(G)→V(H)f: V(G) \to V(H) that preserves adjacency. A planar graph can be drawn in the plane without edge crossings. The chromatic number χ(G)\chi(G) 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 2∣E∣2\lvert E \rvert, 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 V−E+F=2V - E + F = 2, where FF is the number of faces. This topological invariant constrains planar graphs; its corollary E≤3V−6E \le 3V - 6 shows that K5K_5 and K3,3K_{3,3} 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 GG on nn vertices the following are equivalent: GG is a tree; GG is connected with n−1n - 1 edges; GG is acyclic with n−1n - 1 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 K4K_4, 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 K2,3K_{2,3} planar? V=5V = 5 and E=6E = 6, and E≤3V−6=9E \le 3V - 6 = 9 passes. But K2,3K_{2,3} is bipartite, so it has no triangles, which gives the stricter bound E≤2V−4=6E \le 2V - 4 = 6. It passes with equality, so the formula alone does not rule it out, and in fact K2,3K_{2,3} is planar (draw it).

Finally, prove that every tree with n≥2n \ge 2 vertices has at least two leaves (vertices of degree 1). A tree has n−1n - 1 edges, so the sum of degrees is 2(n−1)2(n - 1). If at most one vertex had degree 1, the remaining n−1n - 1 vertices would have degree at least 2, giving a sum of at least 2(n−1)+1>2(n−1)2(n - 1) + 1 > 2(n - 1), a contradiction.

Number theory supplies the arithmetic. a∣ba \mid b, read ”aa divides bb”, means b=akb = ak for some integer kk. The greatest common divisor gcd⁡(a,b)\gcd(a, b) is the largest dd with d∣ad \mid a and d∣bd \mid b. aa is congruent to bb modulo nn when n∣(a−b)n \mid (a - b), and modular arithmetic is arithmetic in Zn={0,1,…,n−1}\mathbb{Z}_n = \{0, 1, \dots, n-1\} with operations taken mod nn. A multiplicative inverse a−1 mod na^{-1} \bmod n exists if and only if gcd⁡(a,n)=1\gcd(a, n) = 1. 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 aa and d>0d > 0 there are unique qq and rr with a=dq+ra = dq + r and 0≤r<d0 \le r < d: every integer lands in a unique “box” relative to dd.
  • Euclidean algorithm. gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b), 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. gcd⁡(a,b)=ax+by\gcd(a, b) = ax + by for some integers x,yx, y, found by the extended Euclidean algorithm: the GCD can always be built as a linear combination of aa and bb.
  • Fermat’s little theorem. If pp is prime and p∤ap \nmid a, then ap−1≡1(modp)a^{p-1} \equiv 1 \pmod p: with a prime modulus, exponentiation is cyclic with period dividing p−1p - 1.
  • RSA. Choose primes p,qp, q. Let n=pqn = pq and φ(n)=(p−1)(q−1)\varphi(n) = (p-1)(q-1). Choose ee with gcd⁡(e,φ(n))=1\gcd(e, \varphi(n)) = 1 and compute d=e−1 mod φ(n)d = e^{-1} \bmod \varphi(n). The public key is (n,e)(n, e) and the private key is dd. Encrypt with c=me mod nc = m^e \bmod n and decrypt with m=cd mod nm = c^d \bmod n. Euler’s theorem guarantees med≡m(modn)m^{ed} \equiv m \pmod n, so encryption and decryption are inverses.

As a worked example, compute gcd⁡(252,105)\gcd(252, 105) with the Euclidean algorithm: 252=2⋅105+42252 = 2 \cdot 105 + 42, 105=2⋅42+21105 = 2 \cdot 42 + 21, 42=2⋅21+042 = 2 \cdot 21 + 0, so gcd⁡(252,105)=21\gcd(252, 105) = 21. The extended version works backwards: 21=105−2⋅42=105−2(252−2⋅105)=5⋅105−2⋅25221 = 105 - 2 \cdot 42 = 105 - 2(252 - 2 \cdot 105) = 5 \cdot 105 - 2 \cdot 252, so 21=(−2)⋅252+5⋅10521 = (-2) \cdot 252 + 5 \cdot 105.

To compute 3100 mod 73^{100} \bmod 7, use Fermat’s little theorem: 36≡1(mod7)3^6 \equiv 1 \pmod 7, and 100=6⋅16+4100 = 6 \cdot 16 + 4, so 3100=(36)16⋅34≡116⋅81≡4(mod7)3^{100} = (3^6)^{16} \cdot 3^4 \equiv 1^{16} \cdot 81 \equiv 4 \pmod 7.

The counting tools extend those of the previous chapter. The inclusion-exclusion principle is ∣A1∪⋯∪An∣=∑∣Ai∣−∑∣Ai∩Aj∣+∑∣Ai∩Aj∩Ak∣−…\lvert A_1 \cup \dots \cup A_n \rvert = \sum \lvert A_i \rvert - \sum \lvert A_i \cap A_j \rvert + \sum \lvert A_i \cap A_j \cap A_k \rvert - \dots: alternately add and subtract to correct for overcounting. The pigeonhole principle says that if n+1n + 1 objects go into nn boxes, some box holds at least 2; more generally, if more than knkn objects go into nn boxes, some box holds at least k+1k + 1. A recurrence relation defines ana_n in terms of earlier terms, as in an=2an−1+1a_n = 2a_{n-1} + 1. For an=c1an−1+c2an−2a_n = c_1 a_{n-1} + c_2 a_{n-2} the characteristic equation is r2=c1r+c2r^2 = c_1 r + c_2, and its roots give the closed form. A generating function A(x)=∑anxnA(x) = \sum a_n x^n 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 r2−c1r−c2=0r^2 - c_1 r - c_2 = 0 has distinct roots r1,r2r_1, r_2, then an=Ar1n+Br2na_n = A r_1^n + B r_2^n, with constants from the initial conditions; with a repeated root rr, an=(A+Bn)rna_n = (A + Bn) r^n. The recurrence behaves like a linear ODE, and its solution is a combination of geometric sequences.
  • Master theorem. For T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n), compare f(n)f(n) with nlog⁡ban^{\log_b a}. If ff grows slower, T=Θ(nlog⁡ba)T = \Theta(n^{\log_b a}); if they match, T=Θ(nlog⁡balog⁡n)T = \Theta(n^{\log_b a} \log n); if ff grows faster, T=Θ(f(n))T = \Theta(f(n)). 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 Dn=n!∑k=0n(−1)k/k!D_n = n! \sum_{k=0}^{n} (-1)^k / k!, approximately n!/en!/e. 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 an=5an−1−6an−2a_n = 5a_{n-1} - 6a_{n-2} with a0=1a_0 = 1, a1=4a_1 = 4: the characteristic equation r2−5r+6=0r^2 - 5r + 6 = 0 has roots 2 and 3, so an=A⋅2n+B⋅3na_n = A \cdot 2^n + B \cdot 3^n. From a0=1a_0 = 1, A+B=1A + B = 1; from a1=4a_1 = 4, 2A+3B=42A + 3B = 4. Solving gives B=2B = 2 and A=−1A = -1, so an=−2n+2⋅3na_n = -2^n + 2 \cdot 3^n.

How many integers from 1 to 1000 are divisible by 2, 3, or 5? ∣A2∣=500\lvert A_2 \rvert = 500, ∣A3∣=333\lvert A_3 \rvert = 333, ∣A5∣=200\lvert A_5 \rvert = 200, ∣A2∩A3∣=166\lvert A_2 \cap A_3 \rvert = 166, ∣A2∩A5∣=100\lvert A_2 \cap A_5 \rvert = 100, ∣A3∩A5∣=66\lvert A_3 \cap A_5 \rvert = 66, and ∣A2∩A3∩A5∣=33\lvert A_2 \cap A_3 \cap A_5 \rvert = 33. By inclusion-exclusion, 500+333+200−166−100−66+33=734500 + 333 + 200 - 166 - 100 - 66 + 33 = 734.

And by pigeonhole, in any group of 13 people at least two share a birth month: 13 people, 12 months.

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 SS that one side counts, then find a different way to count SS 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. (m+nr)=∑k=0r(mk)(nr−k)\binom{m+n}{r} = \sum_{k=0}^{r} \binom{m}{k}\binom{n}{r-k}. Choose rr people from a group of mm men and nn women: the left side counts directly, and the right side splits by choosing kk men and r−kr - k women.
  • Hockey stick identity. (rr)+(r+1r)+⋯+(nr)=(n+1r+1)\binom{r}{r} + \binom{r+1}{r} + \dots + \binom{n}{r} = \binom{n+1}{r+1}. To choose r+1r + 1 elements from {1,…,n+1}\{1, \dots, n+1\}, let the largest chosen element be j+1j + 1 (where j≥rj \ge r), then choose the remaining rr from {1,…,j}\{1, \dots, j\}, giving (jr)\binom{j}{r}. Summing over jj from rr to nn gives the left side.
  • Row sums of Pascal’s triangle. ∑k=0n(nk)=2n\sum_{k=0}^{n} \binom{n}{k} = 2^n. The left side counts the subsets of an nn-element set by size; the right side counts all subsets directly, with 2 choices per element.

Two more worked examples. To prove (nk)=(nn−k)\binom{n}{k} = \binom{n}{n-k}: (nk)\binom{n}{k} counts the ways to choose kk items from nn, and for each such choice the unchosen items form a set of size n−kn - k. That is a bijection between kk-element and (n−k)(n-k)-element subsets, so the counts agree. To prove (2n2)=2(n2)+n2\binom{2n}{2} = 2\binom{n}{2} + n^2: the left side chooses 2 people from 2n2n, with nn in group A and nn in group B. The right side splits the choice into both from A ((n2)\binom{n}{2}), both from B ((n2)\binom{n}{2}), or one from each (n⋅nn \cdot n), for a total of 2(n2)+n22\binom{n}{2} + n^2.

The table pairs each technique with when to reach for it.

TechniqueWhen to useKey formula or idea
BFS/DFS on graphsexplore connectivity, find pathssystematic vertex traversal
Euler’s formulaanalyse planar graphsV−E+F=2V - E + F = 2
Degree-based argumentsprove existence of certain verticeshandshaking: sum of degrees =2∣E∣= 2\lvert E \rvert
Euclidean algorithmcompute a GCD efficientlygcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a,b) = \gcd(b, a \bmod b)
Modular exponentiationcompute ak mod na^k \bmod n efficientlyrepeated squaring
Characteristic equationsolve linear recurrencesfactor rk−c1rk−1−⋯=0r^k - c_1 r^{k-1} - \dots = 0
Generating functionssolve counting problems and recurrencesencode a sequence as a power series
Inclusion-exclusioncount a union of overlapping setsalternately add and subtract intersections
Pigeonhole principleprove existence of collisions or repeatsmore items than containers
Combinatorial proofprove identities without algebracount 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.

  • 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 V−E+F=2V - E + F = 2, which bounds their edges by E≤3V−6E \le 3V - 6.
  • Chromatic number: χ(G)\chi(G), the fewest colours needed to colour the vertices of GG 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 2∣E∣2\lvert E \rvert, 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): gcd⁡(a,b)\gcd(a, b), the largest integer dividing both aa and bb; aa has a multiplicative inverse modulo nn exactly when gcd⁡(a,n)=1\gcd(a, n) = 1.
  • Euclidean algorithm / extended Euclidean algorithm: computes gcd⁡(a,b)\gcd(a, b) by repeating gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b) until the remainder is 0; the extended version also returns x,yx, y with ax+by=gcd⁡(a,b)ax + by = \gcd(a, b), which gives modular inverses.
  • Bezout’s identity: for any integers aa and bb there are integers xx and yy with ax+by=gcd⁡(a,b)ax + by = \gcd(a, b); the extended Euclidean algorithm finds them.
  • Fermat’s little theorem: if pp is prime and does not divide aa, then ap−1≡1(modp)a^{p-1} \equiv 1 \pmod p; it reduces large exponents modulo p−1p - 1 and underlies primality tests and RSA.
  • RSA: a public-key cryptosystem with modulus n=pqn = pq for primes p,qp, q, public exponent ee, and private exponent d=e−1 mod (p−1)(q−1)d = e^{-1} \bmod (p-1)(q-1); encryption is me mod nm^e \bmod n and decryption cd mod nc^d \bmod n, and its security rests on the difficulty of factoring nn.
  • Characteristic equation (recurrences): for a linear recurrence an=c1an−1+c2an−2a_n = c_1 a_{n-1} + c_2 a_{n-2}, the equation r2=c1r+c2r^2 = c_1 r + c_2; with distinct roots r1,r2r_1, r_2 the closed form is an=Ar1n+Br2na_n = A r_1^n + B r_2^n.
  • Generating function: the power series A(x)=∑anxnA(x) = \sum a_n x^n whose coefficients are a sequence; algebra on A(x)A(x) solves counting problems and recurrences.
  • Master theorem: for divide-and-conquer recurrences T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n), comparing f(n)f(n) with nlog⁡ban^{\log_b a} gives T(n)T(n) as Θ(nlog⁡ba)\Theta(n^{\log_b a}), Θ(nlog⁡balog⁡n)\Theta(n^{\log_b a} \log n), or Θ(f(n))\Theta(f(n)), 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 ∑k(nk)=2n\sum_k \binom{n}{k} = 2^n are classic examples.
  • 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 p=5p = 5 and q=11q = 11.