Module contents
Lesson 13 of 22Advanced 120 min

Generating functions and analytic combinatorics

Generating functions turn counting problems into algebra on power series. Study ordinary and exponential generating functions, Catalan, Stirling and Bell numbers, integer partitions, the Flajolet-Sedgewick symbolic method, and asymptotics from the dominant singularity.

After this lesson you can

  • Translate combinatorial constructions such as sums, products, sequences, and sets into generating-function equations.
  • Choose between ordinary and exponential generating functions for unlabelled and labelled objects.
  • Derive formulas for Catalan, Stirling numbers of the second kind, Bell numbers, and integer partitions.
  • Find the asymptotic growth of a sequence from the dominant singularity of its generating function.
  • Implement arithmetic on truncated series and check coefficients against enumeration.

Before you start

Motivation: an infinite sequence in one equation

How many ways can you tile a strip of 1×n1\times n with 1×11\times 1 squares and 1×21\times 2 dominoes? The last piece is either a square or a domino, so the number TnT_n satisfies Tn=Tn−1+Tn−2T_n = T_{n-1} + T_{n-2} with T0=T1=1T_0 = T_1 = 1: Fibonacci, a linear recurrence solved in the previous lesson using its characteristic polynomial. Now change the question: how many binary trees have nn nodes? A nonempty tree is a root with a left subtree of kk nodes and a right subtree of n−1−kn - 1 - k, so

C0=1,Cn=∑k=0n−1Ck Cn−1−k(n≥1).C_0 = 1, \qquad C_n = \sum_{k=0}^{n-1} C_k\,C_{n-1-k} \quad (n \ge 1).

This recurrence is not linear with constant coefficients: each term depends on all preceding terms, multiplied together. No characteristic polynomial will solve it. Yet the answer is as clean as Cn=1n+1(2nn)C_n = \frac{1}{n+1}\binom{2n}{n}.

The tool that finds it is an idea of Abraham de Moivre (1730) and Euler that looks like a trick but turns out to be a language: package the whole sequence into a power series, C(x)=∑nCnxnC(x) = \sum_n C_n x^n. The sum of products ∑kCkCn−1−k\sum_k C_k C_{n-1-k} is exactly the coefficient of xn−1x^{n-1} in C(x)2C(x)^2, and the entire recurrence, including its initial condition, becomes a single quadratic equation:

C(x)=1+x C(x)2.C(x) = 1 + x\,C(x)^2.

One algebraic equation encodes infinitely many numbers. From it we will obtain both the exact formula and the growth, Cn≈4n/(π n3/2)C_n \approx 4^n/(\sqrt{\pi}\,n^{3/2}), read from the geometry of CC in the complex plane.

Why does this matter if you want to build models and systems?

  • Analysis of algorithms. The average number of quicksort comparisons, the average height of a search tree, and the cost of a hash table can be calculated by solving recurrences with generating functions (as in randomized quicksort). They are central to average-case analysis.
  • Probability. The probability generating function E[sX]=∑kP(X=k) sk\E[s^X] = \sum_k \Pr(X = k)\,s^k applies the same idea to a distribution: the generating function of a sum of independent variables is the product of their generating functions, just as for products of classes here.
  • Search spaces. The number of ways to parenthesize a product of n+1n + 1 matrices (the contraction order of a einsum) is CnC_n. Expressions and syntax trees of a given size, and configurations of a grammar, can all be counted this way; their growth tells us whether exhaustive search is feasible.
  • Formal languages and neural networks. Balanced parentheses, the Dyck language, are a classic test of a sequence model’s ability to follow hierarchical structure (Hahn, 2020); counting valid strings of each length is a generating-function question.

We start with formal series, the algebra that makes all this rigorous without discussing convergence; then ordinary generating functions and Catalan numbers; exponential generating functions for labelled objects (Stirling numbers, Bell numbers, and derangements); integer partitions; the symbolic method that unifies them; and finally how the singularity closest to the origin determines growth.

Formal power series

In analysis, a power series is a function defined where it converges. Here we use a more modest and robust object: a sequence with a convenient notation.

The product is the convolution familiar from multiplying polynomials. The observation that makes everything work is that each coefficient of the result is a finite sum: [xn](AB)[x^n](AB) uses only a0,…,ana_0, \dots, a_n and b0,…,bnb_0, \dots, b_n. There are no limits, no convergence, and no xx to evaluate. With these operations K[[x]]K[[x]] is a commutative ring: associativity and distributivity are inherited coefficient by coefficient from polynomials. Here xx is just a placeholder.

That is why ∑n≥0n! xn\sum_{n\ge 0} n!\,x^n, which converges at no x≠0x \neq 0, is a perfectly legitimate member of Q[[x]]\Q[[x]]: it can be added, multiplied, and, as we will see, inverted.

Proof

If AB=1AB = 1, the constant term gives a0b0=1a_0 b_0 = 1, hence a0≠0a_0 \neq 0. Conversely, if a0≠0a_0 \neq 0, the equality AB=1AB = 1 is the infinite system a0b0=1a_0 b_0 = 1 and ∑k=0nakbn−k=0\sum_{k=0}^n a_k b_{n-k} = 0 for n≥1n \ge 1. Solving for bnb_n from the k=0k = 0 term of the nn-th equation gives the stated recursion, determining each bnb_n from b0,…,bn−1b_0, \dots, b_{n-1}. There is exactly one solution.

∎

The fundamental example is the geometric series: (1−x)(1+x+x2+⋯ )=1(1 - x)(1 + x + x^2 + \cdots) = 1, so in K[[x]]K[[x]]

11−x=∑n≥0xn,11−c x=∑n≥0cnxn.\frac{1}{1 - x} = \sum_{n\ge 0} x^n, \qquad \frac{1}{1 - c\,x} = \sum_{n\ge 0} c^n x^n.

By contrast, xx has no inverse: 1/x1/x is not a power series but a Laurent series, which allows negative exponents. If a manipulation leads you to divide by something with no constant term, first factor out xx and check that it cancels.

Composition. If G(0)=g0=0G(0) = g_0 = 0, the composition A(G(x))=∑kak G(x)kA(G(x)) = \sum_k a_k\,G(x)^k is well defined: GkG^k starts at degree kk, so for the coefficient of xnx^n only terms k≤nk \le n contribute, again a finite sum. If g0≠0g_0 \neq 0, it is not generally well defined: the constant term of ∑k(1+x)k/k!\sum_k (1 + x)^k/k! would be ∑k1/k!=e\sum_k 1/k! = e, an infinite sum that is not even rational.

Formal derivative. A′(x)=∑n≥1n anxn−1A'(x) = \sum_{n\ge 1} n\,a_n x^{n-1}, defined coefficient by coefficient. It obeys the product and chain rules, which are polynomial identities in the coefficients, and will let us translate multiplication by nn.

The coefficients need not be rational or integer, but in combinatorics they almost always are. A useful detail: if a0=±1a_0 = \pm 1 and all aka_k are integers, the inverse recursion divides only by ±1\pm 1, so the inverse has integer coefficients. That is why 1/(1−x−x2)1/(1 - x - x^2) produces integers and the implementation below can use exact Python integers.

Ordinary generating functions

The second expression is the important one: each object contributes a monomial xtallax^{\text{talla}}, and grouping by size gives the coefficients. The dictionary between operations on series and on sequences is short and worth keeping handy:

SeriesCoefficient [xn][x^n]Use
A(x)+B(x)A(x) + B(x)an+bna_n + b_ndisjoint union of classes
xkA(x)x^k A(x)an−ka_{n-k} (0 if n<kn \lt k)shift indices
A(x) B(x)A(x)\,B(x)∑k=0nakbn−k\sum_{k=0}^n a_k b_{n-k}pairs of objects whose sizes add
A(x)1−x\dfrac{A(x)}{1 - x}a0+a1+⋯+ana_0 + a_1 + \cdots + a_npartial sums
x A′(x)x\,A'(x)n ann\,a_nmultiply by nn
1(1−x)k\dfrac{1}{(1-x)^{k}}(n+k−1k−1)\binom{n + k - 1}{k - 1}choose with repetition

The last row is the generalized binomial theorem, (1−x)−k=∑n(−kn)(−x)n(1 - x)^{-k} = \sum_n \binom{-k}{n}(-x)^n, or, without formulas, the stars and bars argument: (1+x+x2+⋯ )k(1 + x + x^2 + \cdots)^k chooses an exponent in each of the kk factors, and [xn][x^n] counts solutions of e1+⋯+ek=ne_1 + \cdots + e_k = n with ei≥0e_i \ge 0.

Solving recurrences

The method always has three steps: multiply the recurrence by xnx^n and sum over the nn for which it holds; rewrite each sum using the generating function, incorporating the initial conditions; then solve and extract coefficients, usually using partial fractions.

Notice that the nonhomogeneous term nn required no guess at a “particular solution”: it enters the equation as another series, x/(1−x)2x/(1-x)^2, whose double root at x=1x = 1 produces the term −n−2-n - 2. The previous lesson’s method required guessing the form of a particular solution; this one computes it.

This example is a special case of a theorem connecting this lesson with the previous one.

Proof

Calculate Q(x)A(x)Q(x)A(x). Its coefficient of degree nn is an−c1an−1−⋯−cdan−da_n - c_1 a_{n-1} - \cdots - c_d a_{n-d} (with aj=0a_j = 0 if j<0j \lt 0). The recurrence says exactly that these coefficients vanish for n≥dn \ge d, so P=QAP = QA is a polynomial of degree less than dd. Since Q(0)=1Q(0) = 1, QQ is invertible in K[[x]]K[[x]] and A=P/QA = P/Q. The converse reads the same calculation backward. For the last claim, xdχ(1/x)=1−c1x−⋯−cdxdx^d\chi(1/x) = 1 - c_1 x - \cdots - c_d x^d.

∎

The partial-fraction solution of P/QP/Q and the characteristic-polynomial solution are therefore the same: if χ(t)=∏i(t−ri)mi\chi(t) = \prod_i (t - r_i)^{m_i}, then Q(x)=∏i(1−rix)miQ(x) = \prod_i (1 - r_i x)^{m_i}, and each fraction 1(1−rix)m\frac{1}{(1 - r_i x)^{m}} contributes (n+m−1m−1)rin\binom{n + m - 1}{m - 1} r_i^n, a polynomial in nn times rinr_i^n, as in the preceding lesson. The companion matrix is a third face of the same object: its eigenvalues are the rir_i.

Counting compositions

A composition of nn is an ordered sequence of positive integers summing to nn: 3=2+1=1+2=1+1+13 = 2 + 1 = 1 + 2 = 1 + 1 + 1. Here the generating function appears without any recurrence. If the allowed parts have generating function A(x)=∑kakxkA(x) = \sum_k a_k x^k, with aka_k the number of distinct parts of size kk and a0=0a_0 = 0, then a composition with exactly jj parts is an element of the Cartesian product of jj copies of the set of parts, with size equal to the sum of their sizes. By the product rule applied size by size, these compositions have generating function A(x)jA(x)^j, and summing over jj gives

∑j≥0A(x)j=11−A(x).\sum_{j\ge 0} A(x)^j = \frac{1}{1 - A(x)}.

Strips of squares and dominoes are compositions with parts {1,2}\{1, 2\}, A(x)=x+x2A(x) = x + x^2, and their generating function is 11−x−x2\frac{1}{1 - x - x^2}: Fibonacci, without writing the recurrence. With all positive parts, A=x1−xA = \frac{x}{1-x} and 11−x/(1−x)=1−x1−2x\frac{1}{1 - x/(1-x)} = \frac{1-x}{1-2x}, whose coefficient is 2n−12^{n-1} for n≥1n \ge 1: each of the n−1n - 1 gaps between cells is either cut or left uncut.

InteractiveBuild a generating function from pieces
The 8 objects of size n=5n = 5
111111112112112111222111212221
Coefficients cn=[xn] C(x)c_n = [x^n]\,C(x) (select one to list its objects)
Growth: cnc_n on a logarithmic scale through n=24n = 24; the dashed line has slope log⁡10(1/ρ)\log_{10}(1/\rho)
11010²10³10⁴10⁵06121824
Constructor
Pieces
Variants per size (select to change)
5
A(x)=x+x2A(x) = x + x^{2}
pieces, counted by size
C(x)=11−x−x2C(x) = \frac{1}{1 - x - x^{2}}
sequence of pieces
Recurrencecn=cn−1+cn−2c_n = c_{n-1} + c_{n-2}
[x5] C(x)[x^{5}]\,C(x)8
Enumerated objects8 ✓
c24/c23c_{24}/c_{23}1.6180
1/ρ1/\rho, with A(ρ)=1A(\rho) = 11.6180
Fibonacci: cn=Fn+1c_n = F_{n+1}
Choose the pieces (how many variants of each size, or an infinite family) and how they combine: in a row (sequence), as a multiset, or as a set without repetition. Above are all size-nn objects drawn as strips; the readouts show the class formula and its coefficient, which agrees with brute-force counting. Start with Fibonacci and add the size-3 piece; give the size-1 piece two colors and remove the rest (binary words); then compare 'partitions into distinct parts' with 'partitions into odd parts': what do their coefficients have in common? Also compare c24/c23c_{24}/c_{23} with 1/ρ1/\rho.

The interactive previews the symbolic method: the same collection of pieces yields very different sequences depending on the constructor. The final readout, the ratio cn+1/cnc_{n+1}/c_n, approaches 1/ρ1/\rho, where ρ\rho is the smallest positive root of A(ρ)=1A(\rho) = 1, the point where 11−A(x)\frac{1}{1 - A(x)} blows up. This is our first glimpse of the idea in the lesson’s final section.

Catalan numbers

Return to binary trees. By inductive definition, a binary tree is either the empty tree or a root with an ordered pair of binary trees (left and right). Its size is the number of nodes.

The equation translates the inductive definition term by term: “empty” contributes 11, one object of size 0; “root with two subtrees” contributes xx for the root times C(x)C(x) for the left subtree times C(x)C(x) for the right, because the product of generating functions counts pairs whose sizes add. Solving for CC in a quadratic equation in Q[[x]]\Q[[x]] has two subtleties: choosing the sign of the root and justifying that 1−4x\sqrt{1 - 4x} is a formal series. Both, along with coefficient extraction, are covered by the first guided proof exercise at the end. Here we prove the formula for CnC_n by another, purely combinatorial route, to see both perspectives.

Four faces of the same number

First, why does CnC_n appear everywhere? There are explicit bijections among many families.

  • Dyck paths of semilength nn: sequences of nn up steps U=(1,1)U = (1, 1) and nn down steps D=(1,−1)D = (1, -1) that never go below the axis.
  • Balanced parentheses with nn pairs: the same object, writing UU as “(” and DD as “)”.
  • Binary trees with nn nodes.
  • Triangulations of a convex polygon with n+2n + 2 sides using noncrossing diagonals.

The bijection between paths and trees is the first-return decomposition. A nonempty Dyck path starts with UU; let DD be the step that first returns it to the axis. Between that UU and DD lies a Dyck path wLw_L shifted up by one, followed by another, wRw_R:

w=U wL D wR⟷raıˊz(aˊrbol(wL), aˊrbol(wR)).w = U\,w_L\,D\,w_R \quad\longleftrightarrow\quad \text{raíz}(\text{árbol}(w_L),\ \text{árbol}(w_R)).

Applying the same decomposition recursively builds the whole tree, pairing each node with a matching U…DU \dots D pair. In the polygon, number vertices from 00 to n+1n + 1 and use side (0,n+1)(0, n + 1) as the base. The triangle on the base has a third vertex kk; its left and right subpolygons are the triangulations of the subtrees. The four families satisfy the same equation C=1+x C2C = 1 + x\,C^2 for the same reason, which gives the bijections.

InteractiveFour faces of Catalan
Dyck path and parentheses: w=U wL D wRw = U\,w_L\,D\,w_R
(()())()Convertir este pico en valleConvertir este valle en picoConvertir este pico en valleConvertir este valle en picoEste pico toca la altura 1: no se puede bajar
Binary tree: root, left and right subtrees
Triangulation of the 6-sided polygon
Flip this diagonal (tree rotation)Flip this diagonal (tree rotation)Flip this diagonal (tree rotation)012345
  • selected node: its UU, DD and triangle
  • left subtree wLw_L
  • right subtree wRw_R
4
object 7 of 14
CnC_n14
Parentheses(()())()
Selected node: ∣L∣\lvert L\rvert, ∣R∣\lvert R\rvert2, 1
C4=∑k=03Ck C3−kC_{4} = \sum_{k=0}^{3} C_k\, C_{3-k}
Objects with this split: C2 C1C_{2}\,C_{1}2
The same Catalan object as a Dyck path with its parentheses underneath, a binary tree, and a triangulation. Click a node, triangle, or step: its decomposition w=U wL D wRw = U\,w_L\,D\,w_R is colored across all four views (blue for the node and its U…DU \dots D pair, orange for the left part, aqua for the right). Flip a polygon diagonal: the tree rotates and the path changes. Click a peak or valley (hollow circle) to flip it. Use the player to step through the CnC_n objects; with the root node selected, the readout shows how many objects share its ∣L∣\lvert L\rvert, ∣R∣\lvert R\rvert split.

Notice two things in the figure. First, with the root selected, the “objects with this split” readout is the summand CkCn−1−kC_k C_{n-1-k} in the recurrence; stepping through the CnC_n objects traverses the entire sum, block by block. Second, flipping a polygon diagonal is a tree rotation, the operation used to rebalance AVL and red-black trees. The graph of triangulations joined by flips is the skeleton of a polytope, the associahedron; rotation distance between binary trees is a classical data-structures problem.

The reflection formula

Proof

There are (2nn)\binom{2n}{n} paths from (0,0)(0, 0) to (2n,0)(2n, 0) with nn up steps and nn down steps. The bad paths touch the line y=−1y = -1. Given a bad path, reflect the segment from the origin to its first contact with that line across y=−1y = -1. The new path starts at (0,−2)(0, -2) and ends at (2n,0)(2n, 0), so it has n+1n + 1 up steps and n−1n - 1 down steps. This is invertible: any path from (0,−2)(0, -2) to (2n,0)(2n, 0) crosses y=−1y = -1, and reflecting its segment up to the first crossing recovers a bad path. Thus the number of bad paths equals the number of sequences with n+1n + 1 up steps among 2n2n steps, (2nn+1)\binom{2n}{n+1}. Finally, (2nn+1)=nn+1(2nn)\binom{2n}{n+1} = \frac{n}{n+1}\binom{2n}{n}, and subtraction gives 1n+1(2nn)\frac{1}{n+1}\binom{2n}{n}.

∎

Using Stirling’s formula, (2nn)∼4n/πn\binom{2n}{n} \sim 4^n/\sqrt{\pi n}, so Cn∼4nπ n3/2C_n \sim \frac{4^n}{\sqrt{\pi}\,n^{3/2}}. Remember the shape: exponential growth with base 4 times a polynomial factor n−3/2n^{-3/2}. At the end we will see that 4 comes from the location of the singularity of C(x)C(x) (at x=1/4x = 1/4), while −3/2-3/2 comes from its type, a square root.

Exponential generating functions and labelled objects

So far the objects consisted of indistinguishable pieces: two dominoes are alike. Many important objects have labelled pieces: a permutation of {1,…,n}\{1, \dots, n\}, a partition of the set {1,…,n}\{1, \dots, n\} into blocks, or a graph with numbered vertices. For these, ordinary generating-function products count incorrectly and we need another normalization.

Combining two labelled objects α\alpha (size kk) and β\beta (size n−kn - k) into one of size nn requires distributing the labels {1,…,n}\{1, \dots, n\}: choose which kk go to α\alpha, relabelling them in increasing order, and give the rest to β\beta. There are (nk)\binom{n}{k} ways. Thus the number of combined pairs is

cn=∑k=0n(nk)ak bn−k,es decir,cnn!=∑k=0nakk!⋅bn−k(n−k)!.c_n = \sum_{k=0}^n \binom{n}{k} a_k\,b_{n-k}, \qquad\text{es decir,}\qquad \frac{c_n}{n!} = \sum_{k=0}^n \frac{a_k}{k!}\cdot\frac{b_{n-k}}{(n-k)!}.

The second expression is an ordinary convolution of the sequences an/n!a_n/n! and bn/n!b_n/n!. This suggests dividing by n!n! before packaging.

Three basic exponential generating functions, read as “number of structures of each type on a set of nn labels”:

Structure on nn labelsana_nEGF
a set (one way)11exe^x
a list (linear order)n!n!11−x\dfrac{1}{1 - x}
a cycle (n≥1n \ge 1)(n−1)!(n-1)!log⁡11−x=∑n≥1xnn\log\dfrac{1}{1-x} = \sum_{n\ge 1}\dfrac{x^n}{n}

The missing piece is the set of structures. A set of exactly kk structures of type A\mathcal{A} is a labelled product of kk copies, A^(x)k\hat{A}(x)^k, divided by k!k! because the kk components are unordered. Their labels are disjoint, so the components are always distinct and no symmetries need correcting. Summing over kk:

∑k≥0A^(x)kk!=eA^(x)(si a0=0).\sum_{k\ge 0}\frac{\hat{A}(x)^k}{k!} = e^{\hat{A}(x)} \qquad (\text{si } a_0 = 0).

This exponential formula explains the name. We will use it three times.

Permutations. Every permutation decomposes uniquely into disjoint cycles (the cycle decomposition), so permutations = sets of cycles, and exp⁡(log⁡11−x)=11−x\exp\big(\log\frac{1}{1-x}\big) = \frac{1}{1-x}, the EGF of n!n!. The theory checks itself.

Derangements. A derangement is a permutation with no fixed points: a set of cycles of length at least 2. Its EGF is

D^(x)=exp⁡(log⁡11−x−x)=e−x1−x,Dnn!=∑k=0n(−1)kk!.\hat{D}(x) = \exp\Big(\log\frac{1}{1-x} - x\Big) = \frac{e^{-x}}{1 - x}, \qquad \frac{D_n}{n!} = \sum_{k=0}^{n}\frac{(-1)^k}{k!}.

This is the same formula obtained by inclusion-exclusion, now in one line: Dn/n!D_n/n! are partial sums of the series for e−1e^{-1}, hence Dn/n!→1/eD_n/n! \to 1/e. We will see it again as a pole.

Set partitions: Stirling and Bell

A partition of a set SS is a collection of disjoint nonempty blocks whose union is SS; equivalently, it is an equivalence relation on SS. A block is a “nonempty set,” with EGF ex−1e^x - 1.

Both formulas use the exponential formula: sets of exactly kk blocks, or of any number of blocks. Everything else follows from them.

  • Explicit formula. Expanding (ex−1)k=∑j(kj)(−1)je(k−j)x(e^x - 1)^k = \sum_j \binom{k}{j}(-1)^{j} e^{(k-j)x} and extracting n! [xn]n!\,[x^n] gives S(n,k)=1k!∑j=0k(−1)j(kj)(k−j)nS(n, k) = \frac{1}{k!}\sum_{j=0}^k (-1)^j\binom{k}{j}(k - j)^n. This is inclusion-exclusion for surjections from nn elements to kk, divided by k!k! because the blocks are unnamed.
  • Stirling recurrence. S(n,k)=k S(n−1,k)+S(n−1,k−1)S(n, k) = k\,S(n-1, k) + S(n-1, k-1): element nn either joins one of the kk blocks of a partition of {1,…,n−1}\{1, \dots, n-1\} or forms a block by itself.
  • Bell recurrence, by differentiating the EGF:
B^(x)=eex−1  ⇒  B^′(x)=ex B^(x)\hat{B}(x) = e^{e^x - 1} \;\Rightarrow\; \hat{B}'(x) = e^x\,\hat{B}(x)
Formal chain rule: the derivative of the exponent is e^x.
1/3
nnS(n,1)S(n,1)S(n,2)S(n,2)S(n,3)S(n,3)S(n,4)S(n,4)S(n,5)S(n,5)BnB_n
111
2112
31315
4176115
51152510152

Integer partitions

Now the opposite case: unlabelled objects. A partition of the integer nn writes it as a sum of positive integers, disregarding order: 4=3+1=2+2=2+1+1=1+1+1+14 = 3 + 1 = 2 + 2 = 2 + 1 + 1 = 1 + 1 + 1 + 1. We write the parts in nonincreasing order, λ=(λ1≥λ2≥⋯≥λℓ>0)\lambda = (\lambda_1 \ge \lambda_2 \ge \cdots \ge \lambda_\ell \gt 0).

The product has a direct interpretation: a partition is determined by how many times it uses each part kk, and the factor 11−xk=1+xk+x2k+⋯\frac{1}{1 - x^k} = 1 + x^k + x^{2k} + \cdots chooses that multiplicity (xmkx^{mk} means “mm parts equal to kk”). Expanding the product chooses a term from each factor.

Does an infinite product of formal series make sense? Yes, by the same finiteness argument: for the coefficient of xnx^n only factors with k≤nk \le n matter, because the rest are 1+(teˊrminos de grado>n)1 + (\text{términos de grado} \gt n). The product of the first nn factors already has the final coefficient of xnx^n; in this sense, coefficient by coefficient in the so-called xx-adic topology, the infinite product converges. Restricting parts removes factors: for odd parts, ∏k11−x2k−1\prod_k \frac{1}{1 - x^{2k-1}}; for distinct parts, each part is used zero or one time and the factor is 1+xk1 + x^k:

∑nq(n) xn=∏k≥1(1+xk).\sum_n q(n)\,x^n = \prod_{k\ge 1}(1 + x^k).

Ferrers diagrams and conjugation

A partition can be drawn as a Ferrers diagram: λ1\lambda_1 cells in the first row, λ2\lambda_2 in the second, aligned on the left. Reflection across the diagonal exchanges rows and columns and yields another partition of nn, its conjugate λ′\lambda', with λj′\lambda'_j = the number of parts of λ\lambda that are ≥j\ge j. Reflection is an involution, hence a bijection, proving without calculation:

The number of partitions of nn with at most kk parts equals the number of partitions of nn with all parts ≤k\le k,

because the number of rows of λ\lambda is the length of the first row of λ′\lambda'. The second family has generating function ∏j=1k11−xj\prod_{j=1}^k \frac{1}{1 - x^j}, so the first does too.

The largest square fitting in the corner, the Durfee square, is unchanged by reflection; what remains to its right (the arm) and below it (the leg) are exchanged. Counting by the size dd of that square gives the identity P(x)=∑d≥0xd2∏j=1d(1−xj)2P(x) = \sum_{d\ge 0} \frac{x^{d^2}}{\prod_{j=1}^d (1 - x^j)^2}: a square of d2d^2 cells, an arm that is a partition with at most dd parts, and a leg that is a partition with parts ≤d\le d. By conjugation, the two have the same generating function ∏j=1d11−xj\prod_{j=1}^d \frac{1}{1 - x^j}.

Euler’s theorem and Glaisher’s bijection

The generating-function proof fits on one line, and you will reconstruct it in a guided exercise. Here is J. W. L. Glaisher’s bijective proof (1883). Every integer has a unique representation as d=2emd = 2^e m with mm odd.

  • Distinct to odd. Replace each part d=2emd = 2^e m by 2e2^e parts equal to mm. Repeatedly split each even part in half until none remain.
  • Odd to distinct. If the odd part mm appears rr times, write rr in binary, r=2e1+2e2+⋯r = 2^{e_1} + 2^{e_2} + \cdots with distinct exponents, and replace those rr parts by 2e1m,2e2m,…2^{e_1}m, 2^{e_2}m, \dots. Equivalently, repeatedly merge pairs of equal parts.

The two operations are inverses because binary representation is unique. For example, 15=12+2+115 = 12 + 2 + 1 maps to 3+3+3+3+1+1+13 + 3 + 3 + 3 + 1 + 1 + 1, and back: 3 appears 4=224 = 2^2 times and gives 1212; 1 appears 3=2+13 = 2 + 1 times and gives 2+12 + 1.

InteractiveFerrers diagrams and bijections
64311533211Remove this cellRemove this cellRemove this cellRemove this cellAdd a cell hereAdd a cell hereAdd a cell hereAdd a cell hereAdd a cell here
  • Durfee square (fixed by reflection)
  • arm of λ\lambda (right of square)
  • leg of λ\lambda (below square)
Mode
15
λ\lambda(6, 4, 3, 1, 1)(6,\ 4,\ 3,\ 1,\ 1)
λ′\lambda' (conjugate)(5, 3, 3, 2, 1, 1)(5,\ 3,\ 3,\ 2,\ 1,\ 1)
Parts of λ\lambda = largest part of λ′\lambda'5 = 5
Durfee square3 × 3
Position among p(15)p(15)77 of 176
In 'Conjugate' mode, edit the diagram (remove a corner or fill a dotted gap) and turn on reflection. The Durfee square stays put; the orange arm and aqua leg swap. Find a self-conjugate partition. In 'Glaisher' mode, choose a partition into distinct parts and play it: each even part splits in half until every part is odd. Each row's color represents its odd part mm and stays fixed throughout; playing backward merges equal pairs. Compare the two counts in the readout for each nn.

The pentagonal number theorem

Euler’s product gives an algorithm using O(n2)\bigO(n^2) operations for p(0),…,p(n)p(0), \dots, p(n): multiplying by 11−xk\frac{1}{1 - x^k} is the update cm+=cm−kc_m \mathrel{+}= c_{m-k}, in increasing order of mm. Euler found a better method by studying the inverse, ∏k(1−xk)\prod_k (1 - x^k):

∏k≥1(1−xk)=∑j∈Z(−1)jxj(3j−1)/2=1−x−x2+x5+x7−x12−x15+⋯\prod_{k\ge 1}(1 - x^k) = \sum_{j \in \Z}(-1)^j x^{j(3j-1)/2} = 1 - x - x^2 + x^5 + x^7 - x^{12} - x^{15} + \cdots

The exponents j(3j−1)/2j(3j - 1)/2 are the generalized pentagonal numbers 0,1,2,5,7,12,15,22,26,…0, 1, 2, 5, 7, 12, 15, 22, 26, \dots The most beautiful proof is another bijection, by F. Franklin (1881), pairing partitions into distinct parts with even and odd numbers of parts except in the pentagonal cases; we do not need it here. Multiplying by P(x)P(x) and comparing coefficients:

p(n)=∑j≥1(−1)j+1[p(n−j(3j−1)2)+p(n−j(3j+1)2)],p(n) = \sum_{j\ge 1}(-1)^{j+1}\Big[p\big(n - \tfrac{j(3j-1)}{2}\big) + p\big(n - \tfrac{j(3j+1)}{2}\big)\Big],

with p(m)=0p(m) = 0 if m<0m \lt 0. Each p(n)p(n) uses about 22n/32\sqrt{2n/3} preceding terms, so the complete table costs O(n3/2)\bigO(n^{3/2}) additions.

The symbolic method

For several sections we have been doing the same thing: describing a family of objects using a few operations (union, pairs, sequences, sets) and translating each operation into one on series. Flajolet and Sedgewick turned this practice into a systematic method.

The basic building blocks are the neutral class E\mathcal{E}, one object of size 0 with generating function 11, and the atomic class Z\mathcal{Z}, one object of size 1 with generating function xx. The constructions and their translations are:

ConstructionUnlabelled (OGF)Labelled (EGF)
Disjoint union A+B\mathcal{A} + \mathcal{B}A+BA + BA^+B^\hat{A} + \hat{B}
Product A×B\mathcal{A}\times\mathcal{B}A BA\,BA^ B^\hat{A}\,\hat{B} (label allocation)
Sequence SEQ⁡(A)\operatorname{SEQ}(\mathcal{A})11−A\dfrac{1}{1 - A}11−A^\dfrac{1}{1 - \hat{A}}
Multiset MSET⁡(A)\operatorname{MSET}(\mathcal{A})∏n≥1(1−xn)−an\prod_{n\ge 1}(1 - x^n)^{-a_n}(not applicable)
Set SET⁡(A)\operatorname{SET}(\mathcal{A})∏n≥1(1+xn)an\prod_{n\ge 1}(1 + x^n)^{a_n}eA^e^{\hat{A}}
Cycle CYC⁡(A)\operatorname{CYC}(\mathcal{A})(formula using Euler’s φ\varphi function)log⁡11−A^\log\dfrac{1}{1 - \hat{A}}

The SEQ, MSET, SET, and CYC constructions require a0=0a_0 = 0. In SEQ, MSET, and CYC, a size-0 object would give infinitely many objects of each size, since adding empty objects does not change size, and the series sum ∑jAj\sum_j A^j would cease to be finite coefficient by coefficient: 1/(1−A)1/(1 - A) may still exist in K[[x]]K[[x]] if a0≠1a_0 \ne 1, but no longer counts anything. In SET the count would remain finite (a factor 2a02^{a_0}), and the case is excluded for uniformity; in the labelled case, eA^e^{\hat{A}} with a0≠0a_0 \neq 0 is not even an admissible composition. There are no multisets of labelled objects because two components with disjoint labels are never equal: SET⁡\operatorname{SET} and MSET⁡\operatorname{MSET} coincide.

Proof

Union: the size-nn objects of A+B\mathcal{A} + \mathcal{B} are those of A\mathcal{A} plus those of B\mathcal{B}. Unlabelled product: a pair (α,β)(\alpha, \beta) of size nn consists of an α\alpha of size kk and an β\beta of size n−kn - k for some kk; there are ∑kakbn−k\sum_k a_k b_{n-k}, the coefficient of ABAB. Labelled product: the same count multiplied by the (nk)\binom{n}{k} label allocations, giving the EGF product. Sequence: SEQ⁡(A)=E+A+A×A+⋯\operatorname{SEQ}(\mathcal{A}) = \mathcal{E} + \mathcal{A} + \mathcal{A}\times\mathcal{A} + \cdots is a disjoint union by length, with series ∑jAj\sum_j A^j; since a0=0a_0 = 0, AjA^j starts at degree jj, the sum is finite coefficient by coefficient and equals 1/(1−A)1/(1 - A). Multiset: a multiset is determined by each object’s multiplicity; for each of the ana_n objects of size nn a factor 1/(1−xn)1/(1 - x^n) selects that multiplicity, and the product is finite in each coefficient by the partition argument. Set: the same, with multiplicities 0 or 1 and factor 1+xn1 + x^n. Labelled set: A^k/k!\hat{A}^k/k! by the previous section’s argument, and ∑kA^k/k!=eA^\sum_k \hat{A}^k/k! = e^{\hat{A}}. Labelled cycle: sequences of kk components, A^k\hat{A}^k, grouped by rotation (each cycle of kk components with disjoint labels corresponds to exactly kk sequences), give ∑kA^k/k=log⁡11−A^\sum_k \hat{A}^k/k = \log\frac{1}{1 - \hat{A}}.

∎

With the table, counting reduces to specification. Here are familiar examples and new ones:

ClassSpecificationEquation
Binary treesB=E+Z×B×B\mathcal{B} = \mathcal{E} + \mathcal{Z}\times\mathcal{B}\times\mathcal{B}B=1+xB2B = 1 + xB^2
Plane trees (any number of ordered children)G=Z×SEQ⁡(G)\mathcal{G} = \mathcal{Z}\times\operatorname{SEQ}(\mathcal{G})G=x1−GG = \dfrac{x}{1 - G}
Integer partitionsMSET⁡(SEQ⁡≥1(Z))\operatorname{MSET}(\operatorname{SEQ}_{\ge 1}(\mathcal{Z}))∏k11−xk\prod_k \frac{1}{1 - x^k}
CompositionsSEQ⁡(SEQ⁡≥1(Z))\operatorname{SEQ}(\operatorname{SEQ}_{\ge 1}(\mathcal{Z}))1−x1−2x\dfrac{1 - x}{1 - 2x}
PermutationsSET⁡(CYC⁡(Z))\operatorname{SET}(\operatorname{CYC}(\mathcal{Z}))exp⁡log⁡11−x=11−x\exp\log\frac{1}{1-x} = \frac{1}{1-x}
Set partitionsSET⁡(SET⁡≥1(Z))\operatorname{SET}(\operatorname{SET}_{\ge 1}(\mathcal{Z}))eex−1e^{e^x - 1}
Involutions (cycles of length 1 or 2)SET⁡(CYC⁡1,2(Z))\operatorname{SET}(\operatorname{CYC}_{1,2}(\mathcal{Z}))ex+x2/2e^{x + x^2/2}

The plane-tree equation, G=x/(1−G)G = x/(1 - G), is G−G2=xG - G^2 = x, that is, G=x C(x)G = x\,C(x): plane trees with n+1n + 1 nodes also number CnC_n. Another face of Catalan comes for free from the specification.

A recursive specification such as B=E+Z×B×B\mathcal{B} = \mathcal{E} + \mathcal{Z}\times\mathcal{B}\times\mathcal{B} defines the class as the least fixed point of an operator, just like the inductive definitions in lesson 7. It is solved the same way for series: iterating Bk+1=1+x Bk2B_{k+1} = 1 + x\,B_k^2 from B0=1B_0 = 1 fixes at least one more coefficient at each step, because the factor xx makes the coefficient of degree nn of Bk+1B_{k+1} depend only on degrees below nn of BkB_k. Newton’s method doubles the number of correct coefficients at each step, as the implementation shows.

Asymptotics from singularities

An exact formula does not always exist (there is no closed formula for p(n)p(n) or BnB_n), and when it does, it is not always the useful information: deciding whether exhaustive search is feasible requires knowing how ana_n grows. The central idea of analytic combinatorics is that the generating function, viewed as a complex function, already contains that answer in its singularities.

Now convergence matters. If A(x)=∑anxnA(x) = \sum a_n x^n has radius of convergence R>0R \gt 0, it defines an analytic function on the disk ∣x∣<R\lvert x\rvert \lt R whose Taylor coefficients are the ana_n. Two principles govern growth.

These two principles make up singularity analysis: the dominant singularity’s location gives the exponential base, and its nature gives the polynomial correction. The first is a classical fact of complex analysis: an analytic function’s Taylor series converges on the largest disk where the function is analytic. For the second, consider the two most common cases.

Poles: rational and meromorphic functions

Proof

By partial fractions, A(x)=K1−x/ρ+R(x)A(x) = \frac{K}{1 - x/\rho} + R(x), where RR is a polynomial plus fractions of the form c(1−x/σ)j\frac{c}{(1 - x/\sigma)^{j}} with ∣σ∣≥∣ρ2∣>∣ρ∣\lvert\sigma\rvert \ge \lvert\rho_2\rvert \gt \lvert\rho\rvert. The constant KK is the limit of (1−x/ρ)A(x)(1 - x/\rho)A(x) as x→ρx \to \rho, which by L’Hôpital’s rule equals P(ρ)⋅lim⁡x→ρ1−x/ρQ(x)=P(ρ)⋅−1/ρQ′(ρ)P(\rho)\cdot\lim_{x\to\rho}\frac{1 - x/\rho}{Q(x)} = P(\rho)\cdot\frac{-1/\rho}{Q'(\rho)}. The first term contributes exactly Kρ−nK\rho^{-n}, and each remaining fraction contributes c(n+j−1j−1)σ−n=O(nj−1∣σ∣−n)c\binom{n + j - 1}{j - 1}\sigma^{-n} = \bigO(n^{j-1}\lvert\sigma\rvert^{-n}). Dividing by Kρ−nK\rho^{-n} gives the stated error.

∎

For Fibonacci strips, Q(x)=1−x−x2Q(x) = 1 - x - x^2 has roots ρ=1/φ≈0.618\rho = 1/\varphi \approx 0.618 and −φ≈−1.618-\varphi \approx -1.618, with φ=(1+5)/2\varphi = (1 + \sqrt 5)/2. With P=1P = 1, K=−1ρ(−1−2ρ)=φ/5K = \frac{-1}{\rho(-1 - 2\rho)} = \varphi/\sqrt{5} and

Tn∼φn+15,con error relativo O(φ−2n).T_n \sim \frac{\varphi^{n+1}}{\sqrt 5}, \qquad\text{con error relativo } \bigO(\varphi^{-2n}).

The error decreases exponentially: at n=30n = 30 it is already of order 10−1310^{-13}. Binet’s formula is exactly this with the second pole included.

The same reasoning works if AA is not rational but is meromorphic, analytic except at poles, on a disk larger than ∣ρ∣\lvert\rho\rvert: subtract the singular part of the pole and the remainder is analytic on a larger disk, with exponentially smaller coefficients. Derangements are the perfect example: D^(x)=e−x1−x\hat{D}(x) = \frac{e^{-x}}{1 - x} has a single pole at x=1x = 1, with K=e−1K = e^{-1}. Moreover, D^(x)−e−11−x\hat{D}(x) - \frac{e^{-1}}{1 - x} is entire, so the error is smaller than every exponential: Dn/n!=e−1+O(1/(n+1)!)D_n/n! = e^{-1} + \bigO(1/(n+1)!), and in fact DnD_n is the nearest integer to n!/en!/e for every n≥1n \ge 1.

Square-root singularities

C(x)=1−1−4x2xC(x) = \frac{1 - \sqrt{1 - 4x}}{2x} has no poles: it has a branch point at x=1/4x = 1/4, where the square root stops being analytic. In the complex plane we must cut along [1/4,∞)[1/4, \infty) to define it. Near that point,

C(x)=2−21−4x+O(1−4x).C(x) = 2 - 2\sqrt{1 - 4x} + \bigO(1 - 4x).

The analytic part, 2 and terms with integer powers of 1−4x1 - 4x, does not contribute to the first-order asymptotic; −21−4x-2\sqrt{1 - 4x} dominates. The coefficients of (1−x/ρ)1/2(1 - x/\rho)^{1/2} are known exactly from the generalized binomial theorem and Stirling’s formula:

[xn](1−xρ)1/2=(1/2n)(−1)nρ−n∼−ρ−n2π n3/2.[x^n]\Big(1 - \frac{x}{\rho}\Big)^{1/2} = \binom{1/2}{n}(-1)^n\rho^{-n} \sim -\frac{\rho^{-n}}{2\sqrt{\pi}\,n^{3/2}}.

With ρ=1/4\rho = 1/4 and the factor −2-2: Cn∼4nπ n3/2C_n \sim \frac{4^n}{\sqrt{\pi}\,n^{3/2}}. The base 4=1/ρ4 = 1/\rho comes from the location; n−3/2n^{-3/2} comes from the exponent 1/21/2. The general theorem of Flajolet and Odlyzko (1990), singularity analysis, says that if A(x)∼c (1−x/ρ)αA(x) \sim c\,(1 - x/\rho)^{\alpha} near its unique dominant singularity ρ\rho, with α∉{0,1,2,… }\alpha \notin \{0, 1, 2, \dots\} and AA analytic in a region slightly larger than the disk (a “delta” surrounding ρ\rho), then

an∼cΓ(−α) ρ−n n−α−1.a_n \sim \frac{c}{\Gamma(-\alpha)}\,\rho^{-n}\,n^{-\alpha - 1}.

A simple pole is α=−1\alpha = -1 (factor n0n^0); a double pole, α=−2\alpha = -2 (factor nn); a square root, α=1/2\alpha = 1/2 (factor n−3/2n^{-3/2}, with Γ(−1/2)=−2π\Gamma(-1/2) = -2\sqrt\pi). A recursive “tree-like” specification such as B=1+xB2B = 1 + xB^2 or G=x/(1−G)G = x/(1 - G) produces, under very general conditions (the Drmota-Lalley-Woods theorem for positive, irreducible, aperiodic systems), a square root at the point where the implicit equation ceases to define BB as a function of xx. That is why so many tree families grow like ρ−nn−3/2\rho^{-n}n^{-3/2}.

InteractiveThe dominant singularity
Phase portrait of ff in the complex plane: color = argument of f(x)f(x), rings = scale of ∣f(x)∣\lvert f(x)\rvert
−2−112−ii
Ratio an/an−1a_n/a_{n-1} and root ∣an∣1/n\lvert a_n\rvert^{1/n} against nn; the dashed line is 1/R1/R
  • an/an−1a_n/a_{n-1}
  • ∣an∣1/n\lvert a_n\rvert^{1/n}
  • ±1/R\pm 1/R and convergence disk
Singularities
30
Radius of convergence RR0.6180
Dominant: positive real simple pole at x=0.618x = 0.618.
1/R1/R1.6180
a30/a29a_{30}/a_{29}1.6180
∣a30∣1/30\lvert a_{30}\rvert^{1/30}1.6007
a30a_{30}1.346e6
ana_n / singularity prediction1.0000
Above is the generating function's phase portrait: color gives the argument of f(x)f(x) and rings mark the scale of ∣f(x)∣\lvert f(x)\rvert. All colors meet at a pole; a branch point carries a cut (the thick line on the real axis). The dashed disk is the disk of convergence, reaching the nearest singularity. Below are an/an−1a_n/a_{n-1} and ∣an∣1/n\lvert a_n\rvert^{1/n} against nn. Drag Fibonacci's positive pole toward the origin and watch 1/R1/R rise. Try a dominant negative pole (the ratio alternates sign), a complex pair (the ratio oscillates without converging while the nnth root approaches 1/R1/R), and two nearly equally close poles (very slow convergence). In square-root mode compare the slow convergence of the ratio with a pole, then move the pole closer until it dominates the branch point.

The figure shows three lessons worth keeping:

  1. Only distance from the origin matters. A pole at −0.55-0.55 dominates one at 1.251.25 even on the “wrong” half-axis; coefficients alternate in sign and ∣an∣1/n→1/0.55\lvert a_n\rvert^{1/n} \to 1/0.55.
  2. Several singularities at the same distance cause oscillations: with a complex pair ρe±iθ\rho e^{\pm i\theta}, an≈2∣K∣ρ−ncos⁡(nθ−ϕ)a_n \approx 2\lvert K\rvert\rho^{-n}\cos(n\theta - \phi), the ratio an/an−1a_n/a_{n-1} has no limit, and what survives is the Cauchy-Hadamard theorem: lim sup⁡∣an∣1/n=1/R\limsup \lvert a_n\rvert^{1/n} = 1/R. In the figure’s example the nnth root approaches 1/R1/R, with occasional drops at nn when the cosine passes near zero, but in general even it need not have a limit. With nonnegative coefficients, Pringsheim guarantees that one dominant singularity lies on the positive real axis, but others can lie on the same circle: this occurs for 11−x2\frac{1}{1 - x^2}, whose coefficients are 1,0,1,0,…1, 0, 1, 0, \dots and whose nnth root oscillates between 1 and 0.
  3. Ratio convergence reveals the type. With a simple pole, an/an−1=ρ−1(1+O(∣ρ/ρ2∣n))a_{n}/a_{n-1} = \rho^{-1}(1 + \bigO(\lvert\rho/\rho_2\rvert^n)): geometric convergence. With a square root, an/an−1≈ρ−1(1−32n)a_{n}/a_{n-1} \approx \rho^{-1}(1 - \frac{3}{2n}): convergence at 1/n1/n, the trace of the factor n−3/2n^{-3/2}.

Implementation from scratch

We implement series truncated at degree NN with exact coefficients (Python integers or Fraction), addition, convolution product, inverse by the theorem’s recursion, and composition by Horner’s method. We then use them to check our claims against brute-force enumeration.

[ ]Truncated formal seriesBrowser
from fractions import Fraction
from math import comb, factorial

def _div(x, a0):
    """x / a0 exacto: entero si a0 = ±1, fracción en otro caso."""
    return x * a0 if a0 in (1, -1) else Fraction(x) / a0

class Serie:
    """Serie formal de potencias truncada en grado N, con coeficientes exactos."""

    def __init__(self, coefs, N):
        c = list(coefs)[: N + 1]
        self.c = c + [0] * (N + 1 - len(c))
        self.N = N

    def _lift(self, o):
        return o if isinstance(o, Serie) else Serie([o], self.N)

    def __add__(self, o):
        o = self._lift(o)
        return Serie([a + b for a, b in zip(self.c, o.c)], self.N)

    __radd__ = __add__

    def __neg__(self):
        return Serie([-a for a in self.c], self.N)

    def __sub__(self, o):
        return self + (-self._lift(o))

    def __rsub__(self, o):
        return self._lift(o) - self

    def __mul__(self, o):
        o = self._lift(o)
        out = [0] * (self.N + 1)
        for i, a in enumerate(self.c):            # convolución: [x^n] AB = sum_k a_k b_(n-k)
            if a:
                for j in range(self.N + 1 - i):
                    out[i + j] += a * o.c[j]
        return Serie(out, self.N)

    __rmul__ = __mul__

    def inversa(self):
        a = self.c
        if a[0] == 0:
            raise ZeroDivisionError("no es invertible: el término independiente es 0")
        b = [_div(1, a[0])]
        for n in range(1, self.N + 1):            # sum_k a_k b_(n-k) = 0 para n >= 1
            b.append(_div(-sum(a[k] * b[n - k] for k in range(1, n + 1)), a[0]))
        return Serie(b, self.N)

    def __truediv__(self, o):
        return self * self._lift(o).inversa()

    def __rtruediv__(self, o):
        return self._lift(o) * self.inversa()

    def __pow__(self, k):
        r = Serie([1], self.N)
        for _ in range(k):
            r = r * self
        return r

    def __call__(self, g):
        """Composición self(g(x)); exige g(0) = 0 para que cada coeficiente sea una suma finita."""
        if g.c[0] != 0:
            raise ValueError("composición no definida: g(0) debe ser 0")
        r = Serie([self.c[self.N]], self.N)
        for k in range(self.N - 1, -1, -1):        # Horner
            r = r * g + self.c[k]
        return r

    def __getitem__(self, n):
        return self.c[n]

    def __repr__(self):
        t = [f"{a}" + ("" if k == 0 else "x" if k == 1 else f"x^{k}") for k, a in enumerate(self.c) if a][:8]
        return " + ".join(t) + " + ..."

N = 15
x = Serie([0, 1], N)

# 1) Tiras con cuadrados (1) y dominós (2): T = 1/(1 - x - x^2), frente a la recursión directa
T = 1 / (1 - x - x**2)
def teselas(n):
    return 1 if n <= 1 else teselas(n - 1) + teselas(n - 2)   # la última pieza es 1 o 2
print("teselas   :", T.c[:12])
print("recursión :", [teselas(n) for n in range(12)])

# 2) Composiciones de n: sucesiones de partes >= 1, A = x/(1-x)
A = x / (1 - x)
print("composiciones:", (1 / (1 - A)).c[:10])

# 3) Recurrencia no homogénea a_n = 2 a_(n-1) + n, a_0 = 0
G = x / ((1 - x) ** 2 * (1 - 2 * x))
a = [0]
for n in range(1, N + 1):
    a.append(2 * a[-1] + n)
print("no homogénea:", G.c[:8], " coincide:", G.c == a, " fórmula:", [2 ** (n + 1) - n - 2 for n in range(8)])

# 4) Estrellas y barras: [x^n] 1/(1-x)^3 = C(n+2, 2)
print("estrellas y barras:", (1 / (1 - x) ** 3).c == [comb(n + 2, 2) for n in range(N + 1)])

# 5) Inversa con fracciones y composición con g(0) = 0
print("1/(2 - x) =", 1 / (2 - x))
E = Serie([Fraction(1, factorial(k)) for k in range(N + 1)], N)   # e^x
print("n! [x^n] e^(x/(1-x)):", [int(E(A)[n] * factorial(n)) for n in range(8)])

Everything agrees: the Fibonacci series with its recursion, compositions with 2n−12^{n-1}, the nonhomogeneous recurrence with formula 2n+1−n−22^{n+1} - n - 2, and 1/(1−x)31/(1-x)^3 with stars and bars. The last line composes eye^y with y=x/(1−x)y = x/(1 - x); as an exponential generating function it counts sets of nonempty lists of labels (1,1,3,13,73,…1, 1, 3, 13, 73, \dots): SET⁡(SEQ⁡≥1(Z))\operatorname{SET}(\operatorname{SEQ}_{\ge 1}(\mathcal{Z})).

Now Catalan: solve C=1+xC2C = 1 + xC^2 by fixed-point iteration and Newton’s method, then compare with (2nn)/(n+1)\binom{2n}{n}/(n + 1) and three direct enumerations.

[ ]Catalan: fixed point, Newton, and brute forceBrowser
N = 14
x = Serie([0, 1], N)
cat = [comb(2 * n, n) // (n + 1) for n in range(N + 1)]
correctos = lambda S: sum(1 for n in range(N + 1) if S[n] == cat[n])

C = Serie([1], N)                        # punto fijo C <- 1 + x C^2
iter_fijo = []
for _ in range(N):
    C = 1 + x * C * C
    iter_fijo.append(correctos(C))
print("punto fijo, coeficientes correctos tras cada iteración:", iter_fijo)

C = Serie([1], N)                        # Newton sobre F(C) = 1 + x C^2 - C
iter_newton = []
for _ in range(4):
    C = C + (1 + x * C * C - C) / (1 - 2 * x * C)
    iter_newton.append(correctos(C))
print("Newton:", iter_newton)
print("C_n:", C.c)

def dyck(n):
    out = []
    def rec(s, abiertos, h):
        if len(s) == 2 * n:
            out.append(s)
            return
        if abiertos < n:
            rec(s + "(", abiertos + 1, h + 1)
        if h > 0:
            rec(s + ")", abiertos, h - 1)
    rec("", 0, 0)
    return out

def arboles(n):
    """Árboles binarios con n nodos como tuplas (izq, der); None es el árbol vacío."""
    if n == 0:
        return [None]
    return [(l, r) for k in range(n) for l in arboles(k) for r in arboles(n - 1 - k)]

def parentizaciones(fs):
    if len(fs) == 1:
        return [fs[0]]
    return [f"({a}{b})" for k in range(1, len(fs)) for a in parentizaciones(fs[:k]) for b in parentizaciones(fs[k:])]

print(" n  C_n  Dyck  árboles  parentizaciones")
for n in range(1, 9):
    print(f"{n:2d} {cat[n]:5d} {len(dyck(n)):5d} {len(arboles(n)):7d} {len(parentizaciones('ABCDEFGHI'[: n + 1])):10d}")
print(parentizaciones("ABCD"))

Fixed-point iteration gains exactly one coefficient per step: it starts with two correct coefficients, C0C_0 and C1C_1, and needs fourteen iterations for all fifteen. Newton reaches 3, 7, and 15: it doubles, as over the reals. This is the same Newton method, applied in the ring of series; computer algebra libraries use it to calculate inverses, roots, and exponentials of series in O(M(N))\bigO(M(N)) operations, where M(N)M(N) is the cost of multiplying two series of degree NN.

Exponential generating functions need one more operation: exp⁡(A)\exp(A) for A(0)=0A(0) = 0. Differentiating E=eAE = e^A gives E′=A′EE' = A'E, and comparing coefficients gives n en=∑k=1nk ak en−kn\,e_n = \sum_{k=1}^n k\,a_k\,e_{n-k}: a recursion without factorials or infinite series.

[ ]Exponentials: Bell, Stirling, and derangementsBrowser
from itertools import permutations

def exp_serie(A):
    """exp(A) para A(0) = 0, con la recurrencia de E' = A' E: n e_n = sum_k k a_k e_(n-k)."""
    assert A[0] == 0
    e = [Fraction(1)]
    for n in range(1, A.N + 1):
        e.append(sum(k * A[k] * e[n - k] for k in range(1, n + 1)) / n)
    return Serie(e, A.N)

def a_conteos(S):
    """De función generatriz exponencial a números: n! [x^n]."""
    return [int(S[n] * factorial(n)) for n in range(S.N + 1)]

N = 12
x = Serie([0, 1], N)
ex = exp_serie(x)                                                      # e^x
log_inv = Serie([0] + [Fraction(1, k) for k in range(1, N + 1)], N)   # log 1/(1-x): ciclos

bell = a_conteos(exp_serie(ex - 1))             # SET(SET_{>=1})
perm = a_conteos(exp_serie(log_inv))            # SET(CYC)
desarr = a_conteos(exp_serie(log_inv - x))      # SET(CYC_{>=2})
print("Bell       :", bell)
print("SET(CYC)   :", perm[:9])
print("desarreglos:", desarr)

def stirling2(n, k):
    return int(((ex - 1) ** k)[n] * factorial(n) / factorial(k))
print("S(5, k)    :", [stirling2(5, k) for k in range(6)])

def particiones_conjunto(n):
    """Particiones de {0..n-1} como cadenas de crecimiento restringido: s[i] = bloque de i."""
    out = []
    def rec(s, m):
        if len(s) == n:
            out.append(s)
            return
        for b in range(m + 2):
            rec(s + [b], max(m, b))
    rec([], -1)
    return out

for n in range(1, 9):
    ps = particiones_conjunto(n)
    por_bloques = [sum(1 for p in ps if max(p) + 1 == k) for k in range(n + 1)]
    d = sum(1 for p in permutations(range(n)) if all(p[i] != i for i in range(n)))
    assert len(ps) == bell[n] and d == desarr[n] and por_bloques == [stirling2(n, k) for k in range(n + 1)]
print("Bell, Stirling y desarreglos coinciden con la enumeración hasta n = 8")

# Repartir {1..n} entre dos cajas con nombre: ordinarias frente a exponenciales
print("ordinarias  :", (1 / (1 - x) * (1 / (1 - x))).c[:8])
print("exponenciales:", a_conteos(ex * ex)[:8])

The last two lines put the warning from the exponential section in numbers: the product of ordinary functions gives n+1n + 1, the exponential product gives 2n2^n, and only the latter counts allocations of labels.

For integer partitions, compare the two algorithms from the section (Euler’s product, O(n2)\bigO(n^2), and the pentagonal recurrence, O(n3/2)\bigO(n^{3/2})) with a brute-force generator, and check Euler’s theorem.

[ ]Partitions: Euler, pentagonal numbers, and brute forceBrowser
import time

def p_euler(n):
    """p(0..n) con el producto de Euler: multiplicar por 1/(1 - x^k) es c_m += c_(m-k)."""
    c = [1] + [0] * n
    for k in range(1, n + 1):
        for m in range(k, n + 1):
            c[m] += c[m - k]
    return c

def p_pentagonal(n):
    """p(0..n) con la recurrencia del teorema de los números pentagonales."""
    p = [1] + [0] * n
    for m in range(1, n + 1):
        s, j = 0, 1
        while True:
            g1 = j * (3 * j - 1) // 2
            if g1 > m:
                break
            signo = 1 if j % 2 else -1
            s += signo * p[m - g1]
            g2 = j * (3 * j + 1) // 2
            if g2 <= m:
                s += signo * p[m - g2]
            j += 1
        p[m] = s
    return p

def particiones(n, maximo=None):
    """Genera las particiones de n con partes <= maximo, en orden no creciente."""
    maximo = n if maximo is None else maximo
    if n == 0:
        yield ()
        return
    for k in range(min(n, maximo), 0, -1):
        for resto in particiones(n - k, k):
            yield (k,) + resto

ref = p_euler(25)
print("p(0..15):", ref[:16])
print("fuerza bruta coincide hasta 25:", all(sum(1 for _ in particiones(n)) == ref[n] for n in range(26)))
print("Euler == pentagonal hasta 500:", p_euler(500) == p_pentagonal(500))

n = 1500
t0 = time.perf_counter(); pe = p_euler(n); t1 = time.perf_counter(); pp = p_pentagonal(n); t2 = time.perf_counter()
print(f"p({n}) tiene {len(str(pe[n]))} cifras;  Euler {t1 - t0:.2f} s,  pentagonal {t2 - t1:.2f} s")

dist = [sum(1 for l in particiones(m) if len(set(l)) == len(l)) for m in range(26)]
impa = [sum(1 for l in particiones(m) if all(k % 2 for k in l)) for m in range(26)]
print("distintas:", dist[:16])
print("impares  :", impa[:16], "  iguales hasta 25:", dist == impa)

The pentagonal method is already several times faster at n=1500n = 1500, and the difference grows with nn like n\sqrt n. Python integers are exact at any size: p(1500)p(1500) has 40 digits and there is nothing to round.

Finally, compare each sequence with the asymptotic predicted by its dominant singularity.

[ ]Asymptotics from the dominant singularityBrowser
import math
from decimal import Decimal, getcontext
import numpy as np
import matplotlib.pyplot as plt

ns = np.arange(1, 61)
phi = (1 + 5 ** 0.5) / 2

fib = [1, 1]
for _ in range(70):
    fib.append(fib[-1] + fib[-2])                     # tiras: T_n = F_(n+1)
cat = [comb(2 * n, n) // (n + 1) for n in range(70)]
D = [1, 0]
for n in range(2, 70):
    D.append((n - 1) * (D[-1] + D[-2]))               # desarreglos
P = p_euler(60)

def rel(exacto, aprox):
    return abs(exacto / aprox - 1)

err_fib = [rel(fib[n], phi ** (n + 1) / 5 ** 0.5) for n in ns]                                   # polo simple
err_cat = [rel(cat[n], 4.0 ** n / (math.sqrt(math.pi) * n ** 1.5)) for n in ns]                  # raíz cuadrada
err_der = [rel(D[n], math.factorial(n) / math.e) for n in ns]                                    # polo, resto entero
err_par = [rel(P[n], math.exp(math.pi * math.sqrt(2 * n / 3)) / (4 * n * math.sqrt(3))) for n in ns]

for n in (10, 30, 60):
    print(f"n={n:2d}  Fibonacci {err_fib[n-1]:.1e}  Catalan {err_cat[n-1]:.1e}  "
          f"desarreglos {err_der[n-1]:.1e}  particiones {err_par[n-1]:.1e}")
print("Catalan, n · error relativo:", [round(float(n * err_cat[n - 1]), 3) for n in (10, 30, 60)], "  9/8 =", 9 / 8)

getcontext().prec = 120                                 # D_n = entero más próximo a n!/e, con aritmética exacta
e = Decimal(1).exp()
print("D_n == round(n!/e) para 1 <= n <= 60:", all(abs(Decimal(D[n]) - Decimal(math.factorial(n)) / e) < Decimal("0.5") for n in range(1, 61)))

plt.semilogy(ns, err_fib, label="Fibonacci (polo simple)")
plt.semilogy(ns, err_cat, label="Catalan (raíz cuadrada)")
plt.semilogy(ns, err_par, label="particiones (Hardy-Ramanujan)")
plt.semilogy(ns[:17], err_der[:17], label="desarreglos (polo, resto entero)")
plt.xlabel("n"); plt.ylabel("error relativo de la asintótica"); plt.legend(); plt.show()

The plot separates three regimes. With a pole and a more distant second pole, error decays geometrically (Fibonacci, a straight line on a logarithmic scale until float64 precision is reached near n=35n = 35). With a pole and an entire remainder, error is superexponential (derangements reach float64 precision near n=17n = 17, where their curve is cut off: relative error is of order e/(n+1)!e/(n+1)!). With a square root, error is only O(1/n)\bigO(1/n): nn times the Catalan relative error tends to 9/89/8, the next term in the expansion, Cn=4nπ n3/2(1−98n+O(n−2))C_n = \frac{4^n}{\sqrt\pi\,n^{3/2}}\big(1 - \frac{9}{8n} + \bigO(n^{-2})\big). Hardy-Ramanujan converges more slowly still, with relative error of order 1/n1/\sqrt n.

The library version

sympy has all of the above built in: series expansions, partial fractions, residues, and combinatorial functions. Use it to check calculations and formulas; for large integer tables, your implementation using Python integers is faster and more transparent.

FunctionWhat it does
sp.series(f, x, 0, n)Taylor expansion through xn−1x^{n-1} (a truncated formal series)
sp.apart(f, x)partial fractions of a rational function
catalan(n), bell(n), stirling(n, k)Catalan, Bell, and Stirling numbers (second kind by default)
partition(n)exact p(n)p(n)
sp.residue(f / x**(n+1), x, 0)[xn]f[x^n] f as a residue (Cauchy’s formula)
[ ]sympy against what we knowBrowser
import sympy as sp
from sympy.functions.combinatorial.numbers import catalan, bell, partition, stirling

x = sp.symbols("x")
print(sp.series(1 / (1 - x - x**2), x, 0, 10))
print(sp.series((1 - sp.sqrt(1 - 4 * x)) / (2 * x), x, 0, 8))
print(sp.series(sp.exp(sp.exp(x) - 1), x, 0, 6))         # coeficientes = B_n / n!
print(sp.apart(x / ((1 - x)**2 * (1 - 2 * x)), x))      # fracciones simples
print([catalan(n) for n in range(10)])
print([bell(n) for n in range(10)])
print([partition(n) for n in range(15)], partition(200))
print([stirling(6, k) for k in range(7)])
print(sp.residue(1 / (1 - x - x**2) / x**21, x, 0))     # [x^20] como residuo en 0

# Coma flotante: el producto de Euler en float64 deja de ser exacto en cuanto p(n) supera 2^53
def p_float(n):
    c = np.zeros(n + 1); c[0] = 1.0
    for k in range(1, n + 1):
        for m in range(k, n + 1):
            c[m] += c[m - k]
    return c

pf, pe = p_float(400), p_euler(400)
malos = [n for n in range(401) if int(pf[n]) != pe[n]]
print("primer n con p(n) incorrecto en float64:", malos[0], "  p(n) =", pe[malos[0]], "  2^53 =", 2**53)
print("p(400) exacto :", pe[400])
print("p(400) float64:", int(pf[400]))

The coefficients of sp.series of eex−1e^{e^x - 1} are Bn/n!B_n/n! (5/6=5/3!5/6 = 5/3!, 5/8=15/4!5/8 = 15/4!, 13/30=52/5!13/30 = 52/5!); apart reproduces the partial fractions from the nonhomogeneous recurrence example, and the residue gives T20=10946T_{20} = 10946. The last check shows floating-point error: Euler’s product calculated in float64 gives incorrect values from p(300)=9253082936723602p(300) = 9253082936723602, the first exceeding 2532^{53}; by p(400)p(400) its final five digits are wrong without warning.

Common mistakes

Exercises

NumericChoosing with repetition
Calculate [x6] 1(1−x)4[x^6]\,\dfrac{1}{(1-x)^4}, the number of solutions to e1+e2+e3+e4=6e_1 + e_2 + e_3 + e_4 = 6 with integer ei≥0e_i \ge 0.
NumericMaking change
How many ways can you pay exactly 10 cents with 1-, 2-, and 5-cent coins if only the number of coins of each kind matters, not their order?
QuizIs it a formal series?
Which expressions define an element of Q[[x]]\Q[[x]], with rational coefficients and without discussing convergence?

More than one answer may be correct.

ProofThe Catalan generating function
Prove: Let CnC_n be the number of binary trees with nn nodes and C(x)=∑nCnxnC(x) = \sum_n C_n x^n. Then C(x)=1−1−4x2xC(x) = \dfrac{1 - \sqrt{1 - 4x}}{2x} and Cn=1n+1(2nn)C_n = \dfrac{1}{n+1}\dbinom{2n}{n}.
0
A binary tree is either empty or a root with a left and a right subtree, both binary trees.

Step 1 of 4. What equation does C(x)C(x) satisfy?

NumericThe Bell number B₅
How many ways can the set {1,2,3,4,5}\{1, 2, 3, 4, 5\} be partitioned into nonempty blocks? This is the Bell number B5B_5.
NumericNo one gets their own coat
Six people leave their coats at a coat check, and the coats are returned at random. How many of the 6!=7206! = 720 return orders give nobody their own coat?
NumericPartitions of 10
How many partitions does the integer 10 have, that is, p(10)p(10)?
ProofDistinct and odd parts
Prove: For every n≥0n \ge 0, the number of partitions of nn into distinct parts equals the number of partitions of nn into odd parts.
0
Let D(x)D(x) and O(x)O(x) be the families' ordinary generating functions. It is enough to prove D(x)=O(x)D(x) = O(x) as formal series.

Step 1 of 4. What is D(x)D(x)?

QuizOrdinary or exponential?
You want to count (a) partitions of the set {1,…,n}\{1, \dots, n\} into blocks and (b) partitions of the integer nn. Which generating function suits each problem?
NumericThe growth rate
Let cnc_n count compositions of nn with parts 1, 2, or 3. Suppose cn∼Kαnc_n \sim K\alpha^n. What is α\alpha? Give three decimal places.
QuizWhat ∼ does and does not say
We know Cn∼4nπ n3/2C_n \sim \dfrac{4^n}{\sqrt{\pi}\,n^{3/2}}. Which statements are true?

More than one answer may be correct.

CodeCount partitions exactly
Implement partition_count(n) to return p(n)p(n) as an exact Python int for 0≤n≤2000 \le n \le 200 and beyond, using Euler's product (successively multiplying by 1/(1−xk)1/(1 - x^k)) or the pentagonal recurrence. Do not use floating point or enumerate partitions one by one.
def partition_count(n):
  """Número de particiones del entero n >= 0, exacto (int de Python)."""
  # tu código: producto de Euler (c[m] += c[m - k]) o recurrencia pentagonal
  return 0
Shift+Enter to run

Summary

Key idea
A generating function turns the structural description of a family of objects into an algebraic equation: formal power-series algebra gives exact counts, and the location and type of the dominant singularity give their growth.
  • Formal series K[[x]]K[[x]] are sequences with convolution as their product. They need no convergence because each coefficient is a finite sum: AA is invertible if and only if a0≠0a_0 \neq 0, and A(G)A(G) is defined if G(0)=0G(0) = 0.
  • Ordinary functions for unlabelled objects: union, product, and sequence translate to A+BA + B, ABAB, and 1/(1−A)1/(1 - A). Linear recurrences correspond exactly to rational functions, and partial fractions reproduce the characteristic-polynomial method.
  • Catalan: C=1+xC2C = 1 + xC^2 gives Cn=1n+1(2nn)C_n = \frac{1}{n+1}\binom{2n}{n}, counting binary trees, Dyck paths, parentheses, triangulations, and parenthesizations, all linked by the decomposition w=U wL D wRw = U\,w_L\,D\,w_R.
  • Exponential functions for labelled objects: the product includes label allocation and sets translate to eAe^{A}. This yields eex−1e^{e^x - 1} (Bell), (ex−1)k/k!(e^x - 1)^k/k! (Stirling), and e−x/(1−x)e^{-x}/(1 - x) (derangements).
  • Integer partitions: ∏k1/(1−xk)\prod_k 1/(1 - x^k); Ferrers conjugation, Euler’s theorem (distinct parts = odd parts), and the pentagonal recurrence, which computes p(n)p(n) in O(n3/2)\bigO(n^{3/2}).
  • The symbolic method translates specifications (SEQ, MSET, SET, CYC) into equations automatically.
  • Asymptotics: 1/R1/R (distance to the nearest singularity) gives the exponential base; a simple pole gives Kρ−nK\rho^{-n} with exponentially small error, while a square root gives ρ−nn−3/2\rho^{-n}n^{-3/2} with error O(1/n)\bigO(1/n). Compute coefficients with exact integers and use floating point only for asymptotic comparisons.