Bell Number in Java
In this section, we will learn what is bell number and also create Java programs to check if the given number is a bell number or not. The bell number program frequently asked in Java coding interviews and academics.
Bell Number
The Bell numbers are a sequence of numbers that describe the number of ways a set with N elements can be partitioned into disjoint, non-empty subsets.
It is used to represents the number of ways a set (no-empty) of n elements can be partitioned into a subset. It is also known as exponential numbers. In other words, we can say that a bell number is a number of partitions of a set.
It is an OEIS sequence A000110. First few Bell numbers are 1, 1, 2, 5, 15, 52, 203, 877, 4140, etc.
Bell Number Example
Consider a set of alphabets {a, b, c}. The set has three elements. Let’s find the subset of the given set.
We observe that a bell number gives the value of sum of (n, k) for all values of k. Where k ranging from 1 to n and the set (n, k) is the number of partitioned of n elements into k subsets.
Mathematically, we can write it as follows:
Methods to Find Bell Numbers
There are the following three methods to find bell numbers:
- Using Dobinski’s Formula
- Sum of Sterling Number of Second Kind
- Using Peirce or Bell Triangle
Using Dobinski’s Formula
We can find the nth bell number by using the following Dobinski’s formula:
Algorithm
Sum of Stirling Number of Second Kind
Compute sum(n, k). Where, k=1 to n and sum of all values of the numbers. The (n, k) is a Stirling number of the second kind.
We can find the Stirling number by using the following formula:
The Stirling number will be 1 if n==k or k=1.
Algorithm
Using Peirce or Bell Triangle
Using the bell triangle is the best way to find bell numbers. It is a triangle of numbers just like the Pascal triangle. It counts the partitions of a set-in which a given element is the largest singleton. It is named for its close connection to the Bell numbers, which may be found on both sides of the triangle, and which are in turn named after Eric Temple Bell.
The following triangle is used to find bell numbers.
Let’s see how it is calculated.
- Begin with the number 1 and put it on a row (x0,1 = 1) by itself.
- In the next row, write the rightmost element of the previous row. The rightmost number becomes the leftmost element of the new row.
- Determine the numbers not on the left column by taking the sum of the number to the left and the number above the number to the left, that is, the number diagonally up and left of the number we are calculating.
- Repeat the above step until there is a new row with one more number than the previous row.
- The number on the left-hand side presented in the row is a bell number for that row.
Let’s implement the above logic in a Java program.
Bell Number Java Program
BellNumberExample1.java
Output:
BellNumberExample2.java
Output: