Bell numbers are named after Eric Temple Bell and form a sequence of integers in combinatorics. They begin as follows (OEIS A000110:
is the number of partitions of a set with cardinality . A partition of a set is defined as a family of pairwise disjoint nonempty subsets of whose union is . For example, because the set of 3 elements has 5 different partitions:
is 1 because the empty set has exactly 1 partition.
Recurrence
The Bell numbers satisfy the recurrence:
Proof:
is the number of partitions of a set containing elements. Let the set for be and the set for be . Thus, can be regarded as being obtained from by adding one element, . Consider the element .
-
If it is placed in a class by itself, elements remain, and the number of partitions in this case is ;
-
If it is placed in a class with some 1 element, elements remain, and the number of partitions in this case is ;
-
If it is placed in a class with some 2 elements, elements remain, and the number of partitions in this case is ;
-
...
Continuing in this way gives the formula above.
Each Bell number is the sum of the corresponding Stirling numbers of the second kind. The Stirling numbers of the second kind are the number of ways to partition a set of cardinality into exactly nonempty sets.
Bell Triangle
Construct a triangular matrix as follows (in a form similar to Pascal's triangle):
- ;
- For , the first entry of row equals the last entry of the previous row, namely ;
- For , the -th row's -th entry equals the sum of the entry to its left and the one to its upper left, namely .
Some results are as follows:
The first entry of each row is a Bell number. The Bell numbers can be computed recursively using this triangle.
Reference implementation
C++
constexpr int MAXN = 2000 + 5;
int bell[MAXN][MAXN];
void f(int n) {
bell[0][0] = 1;
for (int i = 1; i <= n; i++) {
bell[i][0] = bell[i - 1][i - 1];
for (int j = 1; j <= i; j++)
bell[i][j] = bell[i - 1][j - 1] + bell[i][j - 1];
}
}
Python
MAXN = 2000 + 5
bell = [[0 for i in range(MAXN + 1)] for j in range(MAXN + 1)]
def f(n):
bell[0][0] = 1
for i in range(1, n + 1):
bell[i][0] = bell[i - 1][i - 1]
for j in range(1, i + 1):
bell[i][j] = bell[i - 1][j - 1] + bell[i][j - 1]
Exponential Generating Function
Consider the exponential generating function of the Bell numbers and its derivative:
By the recurrence for the Bell numbers, we obtain:
This is a convolution, so:
This is a differential equation, whose solution is:
Finally, when , . Substituting gives , yielding the closed form of the exponential generating function of the Bell numbers:
After preprocessing through its first terms, one polynomial exp operation yields the first Bell numbers. The bottleneck is the polynomial exp operation, so the time complexity can be .