Find all even length binary sequences with same sum of first and second half bits | Iterative | C ++ implementation ; Function to convert the number into binary and store the number into an array ; Function to check if the sum of the digits till the mid of the array and the sum of the digits from mid till n is the same , if they are same then print that binary ; Calculating the sum from 0 till mid and store in sum1 ; Calculating the sum from mid till n and store in sum2 ; If sum1 is same as sum2 print the binary ; Function to print sequence ; Creating the array ; Looping over powers of 2 ; Converting the number into binary first ; Checking if the sum of the first half of the array is same as the sum of the next half ; Driver Code
#include <iostream> NEW_LINE #include <malloc.h> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void convertToBinary ( int num , int a [ ] , int n ) { int pointer = n - 1 ; while ( num > 0 ) { a [ pointer ] = num % 2 ; num = num / 2 ; pointer -- ; } } void checkforsum ( int a [ ] , int n ) { int sum1 = 0 ; int sum2 = 0 ; int mid = n / 2 ; for ( int i = 0 ; i < mid ; i ++ ) sum1 = sum1 + a [ i ] ; for ( int j = mid ; j < n ; j ++ ) sum2 = sum2 + a [ j ] ; if ( sum1 == sum2 ) { for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] ; cout << " STRNEWLINE " ; } } void print_seq ( int m ) { int n = ( 2 * m ) ; int a [ n ] ; for ( int j = 0 ; j < n ; j ++ ) { a [ j ] = 0 ; } for ( int i = 0 ; i < ( int ) pow ( 2 , n ) ; i ++ ) { convertToBinary ( i , a , n ) ; checkforsum ( a , n ) ; } } int main ( ) { int m = 2 ; print_seq ( m ) ; return 0 ; }