Count even length binary sequences with same sum of first and second half bits in C++


We are given several bits n as input for a binary sequence. The goal here is to find the binary sequence of length 2n such that the sum of its first and second half bits is equal. First n bits and next n bits have the same sum.

We have a binary sequence so the only choice to put digits at any place is 0 and 1. For n bits at first and second half, no. of possible combinations are −

n bits with all zeros (0 1’s) nC0= 1

n bits with 1 1’s nC1

n bits with 2 1’s nC2

.

.

n bits with n 1’s nCn

For 2n bits

  • First half with 0 1’s and second half with 0 1’s nC0 X nC0

  • First half with 1 1’s and second half with 1 1’s nC1 X nC1

  • First half with 2 1’s and second half with 2 1’s nC2 X nC2

  • ..............

  • First half with n 1’s and second half with n 1’s nCn X nCn

Total such combinations= nC0*nC0 + nC1*nC1+.......+nCn*nCn

=(nC0)2+(nC1)2+...........+(nCn)2

Input

n=1

Output

Sequences with same sum of first and second half bits: 2

Explanation − Possible 2*1=2 bit sequences 00,01,10,11 Out of these four 01 and 10 have sum=1

Input

n=2

Output

Sequences with same sum of first and second half bits: 6

Explanation − Possible 2*2 = 4-bit sequences 0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111

Out of these sequences with sum of first 2 and last 2 bits is same −

0000,0101,0110,1001,1010,1111, total=6

Approach used in the below program is as follows

  • Integer ‘bits’ stores the number.

  • Function findSeq(int n) takes n as input and returns the count of sequences with above sum of first and second half 2n bits equal.

  • Variable nCi is used to store the initial value =1 as nC0 is 1.

  • Initialize ans=0, which will count such sequences as sum of nCi*nCi.

  • Starting from i=0 to n add nCi*nCi to the ans, calculate each nCi as above formula.

  • After the end of for loop return the result present in ‘ans’ as count.

Example

 Live Demo

#include<iostream>
using namespace std;
// Returns the count of even length sequences
int findSeq(int n){
   int nCi=1; //nC0=1
   int ans = 1;
   for (int i = 1; i<=n ; i++){
      //nCi=(nCi-1)*(nCi/nCi-1)
      // nCi/nC(i-1) = (n+1-i)/i;
      nCi = (nCi * (n+1-i))/i;
      ans += nCi*nCi;
   }
   return ans;
}
int main(){
   int bits = 2;
   cout << "Count of binary sequences such that sum of first and second half bits is
   same: "<<findSeq(bits);
   return 0;
}

Output

Count of binary sequences such that sum of first and second half bits is same: 6

Updated on: 28-Jul-2020

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements