Generate an array of given size with equal count and sum of odd and even numbers | C ++ implementation to find the array containing same count of even and odd elements with equal sum of even and odd elements ; Function to find the array such that the array contains the same count of even and odd elements with equal sum of even and odd elements ; Length of array which is not divisible by 4 is unable to form such array ; Loop to find the resulted array containing the same count of even and odd elements ; Find the total sum of even elements ; Find the total sum of odd elements ; Find the difference between the total sum of even and odd elements ; The difference will be added in the last odd element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSolution ( int N ) { if ( N % 4 != 0 ) cout << -1 << " STRNEWLINE " ; else { int temp = 0 , sum_odd = 0 , sum_even = 0 ; int result [ N ] = { 0 } ; for ( int i = 0 ; i < N ; i += 2 ) { temp += 2 ; result [ i + 1 ] = temp ; sum_even += result [ i + 1 ] ; result [ i ] = temp - 1 ; sum_odd += result [ i ] ; } int diff = sum_even - sum_odd ; result [ N - 2 ] += diff ; for ( int i = 0 ; i < N ; i ++ ) cout << result [ i ] << " ▁ " ; cout << " STRNEWLINE " ; } } int main ( ) { int N = 8 ; findSolution ( N ) ; return 0 ; }