Count of ways N elements can form two different sets containing N/2 elements each
Given a number N, representing count of elements and is equal to 2K, the task is to find the number of ways these elements can be form 2 sets containing K elements each.
Examples:
Input: N = 4
Output: 3
Explanation: The 3 sets consisting of 2 (= N/2) elements are:
[1, 2], [3, 4]
[1, 3], [2, 4]
[1, 4], [2, 3]
Input: N = 20
Output: 12164510040883200
Approach: It is to be observed that the concept of combinations has to apply in order to choose the elements for each set.
It is known that the number of ways to choose r things from a total of n things is given by:
nCr = n!/(n-r)!*r!
Now, the above formula can be modified to solve the given problem:
- Here, N/2 elements have to be chosen from N elements to form each set. Hence, r = N/2.
- It is to be noted that the same element cannot be simultaneously present in the two sets. So, the formula of nCr has to be divided by 2.
- Also, the element present in each set can arrange themselves in (N/2-1)! ways. Since there are two sets, the formula will be multiplied by this factor twice.
The modified formula obtained is given by:
Number of ways = ((N! / (N – r)!*r!) / 2) * (N / 2 – 1)!*(N / 2 – 1)! where r = N / 2
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
long long int fact( long long int N)
{
if (N == 0) {
return 1;
}
else {
return N * fact(N - 1);
}
}
int main()
{
int N = 20;
cout << (fact(N) / (fact(N / 2)
* fact(N - N / 2)))
/ 2
* fact(N / 2 - 1)
* fact(N / 2 - 1);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static long fact( long N)
{
if (N == 0 ) {
return 1 ;
}
else {
return N * fact(N - 1 );
}
}
public static void main(String[] args)
{
int N = 20 ;
System.out.println(
(fact(N) / (fact(N / 2 ) * fact(N - N / 2 ))) / 2
* fact(N / 2 - 1 ) * fact(N / 2 - 1 ));
}
}
|
Python3
def fact(N):
if (N = = 0 ):
return 1
else :
return N * fact(N - 1 )
if __name__ = = "__main__" :
N = 20
print ( int ((fact(N) / (fact(N / 2 ) * fact(N - N / 2 ))) /
2 * fact(N / 2 - 1 ) * fact(N / 2 - 1 )))
|
C#
using System;
public class GFG
{
static long fact( long N)
{
if (N == 0) {
return 1;
}
else {
return N * fact(N - 1);
}
}
public static void Main( string [] args)
{
int N = 20;
Console.WriteLine(
(fact(N) / (fact(N / 2) * fact(N - N / 2))) / 2
* fact(N / 2 - 1) * fact(N / 2 - 1));
}
}
|
Javascript
<script>
function fact(N)
{
if (N == 0) {
return 1;
}
else {
return N * fact(N - 1);
}
}
let N = 20;
document.write((fact(N) / (fact(N / 2)
* fact(N - N / 2)))
/ 2
* fact(N / 2 - 1)
* fact(N / 2 - 1));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
01 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...