# Ways to select one or more pairs from two different sets in C++

In this problem, we are given two positive numbers n and m (n <= m) which is the total number of items of two sets respectively. Our task is to find the total number of ways to select pairs (one or more) from the items of these sets.

Let’s take an example to understand the problem,

## Input

2 2

## Output

6

## Explanation

we have two sets both with two elements

Set A = {1, 2}
Set B = {3, 4}

Way to arrange one pair at a time,(1..3), (1...4), (2..3), (2...4)

Ways to arrange two pairs at a time,(1...3, 2...4) , (1...4, 2...3)

To solve this problem, we will use combinations of elements of the sets. The following is a simple combination formula that can find the count.

Ways = Σn i=1n Ci* mCi* i!
= Σni=1 ( nPi * mPi) /i

Program to show the implementation of our solution,

## Example

Live Demo

#include <iostream>
using namespace std;
int* fact, *inverseMod;
const int mod = 1e9 + 7;
int power(int x, int y, int p){
int res = 1;
x = x % p;
while (y) {
if (y & 1)
res = (1LL * res * x) % p;
y = y >> 1;
x = (1LL * x * x) % p;
}
return res;
}
void calculate(int n){
fact = inverseMod = 1;
for (int i = 1; i <= n; ++i) {
fact[i] = (1LL * fact[i - 1] * i) % mod;
inverseMod[i] = power(fact[i], mod - 2, mod);
}
}
int nPr(int a, int b) {
return (1LL * fact[a] * inverseMod[a - b]) % mod;
}
int selectPairCount(int n, int m){
fact = new int[m + 1];
inverseMod = new int[m + 1];
calculate(m);
int ans = 0;
for (int i = 1; i <= n; ++i) {
ans += (1LL * ((1LL * nPr(n, i)
* nPr(m, i)) % mod)
* inverseMod[i]) % mod;
if (ans >= mod)
ans %= mod;
}
return ans;
}
int main() {
int n = 2, m = 2;
cout<<"The number of ways to select pairs is : "<<selectPairCount(n, m);
return 0;
}

## Output

The number of ways to select pairs is : 6