Number of ways of distributing N identical objects in R distinct groups
Given two integers N and R, the task is to calculate the number of ways to distribute N identical objects into R distinct groups.
Examples:
Input: N = 4, R = 2
Output: 5
No of objects in 1st group = 0, in second group = 4
No of objects in 1st group = 1, in second group = 3
No of objects in 1st group = 2, in second group = 2
No of objects in 1st group = 3, in second group = 1
No of objects in 1st group = 4, in second group = 0
Input: N = 4, R = 3
Output: 15
Approach: Idea is to use Multinomial theorem. Let us suppose that x1 objects are placed in the first group, x2 objects are placed in the second group and xR objects are placed in the Rth group. It is given that,
x1 + x2 + x3 +…+ xR = N
The solution of this equation by multinomial theorem is given by N + R – 1CR – 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int ncr( int n, int r)
{
int ans = 1;
for ( int i = 1; i <= r; i += 1)
{
ans *= (n - r + i);
ans /= i;
}
return ans;
}
int NoOfDistributions( int N, int R)
{
return ncr(N + R - 1, R - 1);
}
int main()
{
int N = 4, R = 3;
cout << NoOfDistributions(N, R);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int ncr( int n, int r)
{
int ans = 1 ;
for ( int i = 1 ; i <= r; i += 1 )
{
ans *= (n - r + i);
ans /= i;
}
return ans;
}
static int NoOfDistributions( int N, int R)
{
return ncr(N + R - 1 , R - 1 );
}
public static void main(String[] args)
{
int N = 4 , R = 3 ;
System.out.println(NoOfDistributions(N, R));
}
}
|
Python3
def ncr(n, r):
ans = 1
for i in range ( 1 , r + 1 ):
ans * = (n - r + i)
ans / / = i
return ans
def NoOfDistributions(N, R):
return ncr(N + R - 1 , R - 1 )
N = 4
R = 3
print (NoOfDistributions(N, R))
|
C#
using System;
class GFG {
static int ncr( int n, int r)
{
int ans = 1;
for ( int i = 1; i <= r; i += 1)
{
ans *= (n - r + i);
ans /= i;
}
return ans;
}
static int NoOfDistributions( int N, int R)
{
return ncr(N + R - 1, R - 1);
}
static public void Main()
{
int N = 4, R = 3;
Console.WriteLine(NoOfDistributions(N, R));
}
}
|
Javascript
<script>
function ncr(n, r)
{
let ans = 1;
for (let i = 1; i <= r; i += 1)
{
ans *= (n - r + i);
ans = parseInt(ans / i);
}
return ans;
}
function NoOfDistributions(N, R)
{
return ncr(N + R - 1, R - 1);
}
let N = 4, R = 3;
document.write(NoOfDistributions(N, R));
</script>
|
Time Complexity: O(R)
Auxiliary Space: O(1)
Last Updated :
31 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...