Bell Numbers - Number of ways to Partition a Set in C++

C++Server Side ProgrammingProgramming

A bell number is used to denote the number of ways a set of n elements can be partitioned into subsets that are not empty (i.e. have at least one element).

In this program, we are given a set of n elements and we have to find the number of ways to partition the set into non-empty subsets.

Example

Input : 3
Output : 5

Explanation − let the set of three elements {1, 2, 3}.

The subsets are {{1} , {2} , {3}} ; {{1} , {2,3}} ; {{1 , 2} , {3}} ; {{2} , {1 , 3}} ; {1 , 2 , 3}.

Bell number: A bell number bell(n) gives the value of sum of s(n,k) for all values of k ranging from 1 to n. Here s(n,k) is the number of partitions of n elements into k subsets.

The formula would be −

$$bell(n)=\sum_{k=0}^n S(n,k)$$

The function s(n,k) is recursively as −

s(n+1,k) = k*s(n,k) + s(n,k-1).

Working

On adding (n+1)th element to k partitions, there are two possibilities −

  • It adds one to the k partitions of existing partitions i.e. s(n,k-1).

  • Adding value to all sets of partition, i.e. k*s(n,k).

First few Bell numbers are 1 , 1 , 2 ,5 ,15 , 52 , 205

For finding the Bells number, we have a few methods,

  • Simple method is to one by one compute s(n,k) for k = 1 to n and add sum of all values of the number.

  • Using bell triangle is to use bell’s triangle as given below −

1
1  2
2  3  5
5  7  10  15
15 20 27  37 52

Example

#include<iostream>
using namespace std;
int bellNumber(int n) {
   int bell[n+1][n+1];
   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];
   }
   return bell[n][0];
}
int main() {
   for (int n=0; n<=5; n++)
   cout<<"Bell Number "<<n<<" is "<< bellNumber(n)<<endl;
   return 0;
}
raja
Published on 22-Nov-2019 07:21:06
Advertisements