Print all the combinations of N elements by changing sign such that their sum is divisible by M in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of N elements. And need to return all the sums of the elements are divisible by an integer M.

Input : array = {4, 7, 3} ; M = 3
Output : 5+4+3 ; 5+4-3

To solve this problem, we need to know the concept of a power set that can be used to find all the possible sums obtained. From this sum, print all those which are divisible by M.

Algorithm

Step 1: Iterate overall combinations of ‘+’ and ‘-’ using power set.
Step 2: If the sum combination is divisible by M, print them with signs.

Example

 Live Demo

#include <iostream>
using namespace std;
void printDivisibleSum(int a[], int n, int m){
   for (int i = 0; i < (1 << n); i++) {
      int sum = 0;
      int num = 1 << (n - 1);
      for (int j = 0; j < n; j++) {
         if (i & num)
            sum += a[j];
         else
            sum += (-1 * a[j]);
         num = num >> 1;
      }
      if (sum % m == 0) {
         num = 1 << (n - 1);
         for (int j = 0; j < n; j++) {
            if ((i & num))
               cout << "+ " << a[j] << " ";
            else
               cout << "- " << a[j] << " ";
            num = num >> 1;
         }
         cout << endl;
      }
   }
}
int main(){
   int arr[] = {4,7,3};
   int n = sizeof(arr) / sizeof(arr[0]);
   int m = 3;
   cout<<"The sum combination divisible by n :\n";
   printDivisibleSum(arr, n, m);
   return 0;
}

Output

The sum combination is divisible by n −

- 4 + 7 - 3
- 4 + 7 + 3
+ 4 - 7 - 3
+ 4 - 7 + 3
raja
Published on 17-Jan-2020 10:14:04
Advertisements