# Counting pairs when a person can form pair with at most one in C++

C++Server Side ProgrammingProgramming

We are given with N no. of participants in a coding competition. The goal is to find the no. of pairs that are possible when a person can pair with at most one other person. So a pair has at most 2 participants. The participants are allowed to take part alone also.

We can solve this using recurrence where pairs=

• count=1 when n=0 or 1 ( only one person left )

• if person remains single n reduced to n-1

• now for remaining pairing people left = n-2

count=makePairs(p-1) + (p-1)*makePairs(p-2);

Let’s understand with examples.

Input − persons=3

Output − Count of ways to make pair − 4

Explanation

If three persons are a,b,c then ways of pairing could be:
(a,b), (c) → c remained single
(a,c), (b) → b remained single
(b,c), (a) → a remained single
(a),(b),(c) → all remained single
Total ways = 4

Input − persons=2

Output − Count of ways to make pair − 2

Explanation

I persons are a,b then ways of pairing could be −
(a,b) → both paired
(a),(b) → both remained single
Total ways = 2

## Approach used in the below program is as follows

• We take an integer person to store the number of participants.

• Function makePairs(int p) takes no. of persons as input and returns the count of ways in which they can pair themselves.

• Take the initial count as 0.

• If p=0 or 1 then the only way is 1 to remain single.

• Else person can chose to remain single, then remaining (p-1) will find pairs using (p1)*makePairs(p-2).

• Final value of count is returned as no. of ways of pairing at the end.

## Example

Live Demo

#include<iostream>
using namespace std;
int makePairs(int p){
int count=0;
// Base condition
if (p==0 || p==1)
{ count=1; }
else
{ count=makePairs(p-1) + (p-1)*makePairs(p-2); }
return count;
}
int main(){
int persons = 5;
cout <<"Number of ways to make pair ( or remain single ):"<<makePairs(persons);
return 0;
}

## Output

If we run the above code it will generate the following output −

Number of ways to make pair ( or remain single ): 26
Updated on 29-Aug-2020 09:08:11