- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

#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

- Related Questions & Answers
- Print n numbers such that their sum is a perfect square
- Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N in C++
- Find an array element such that all elements are divisible by it using c++
- Count of m digit integers that are divisible by an integer n in C++
- Sum which is divisible by n in JavaScript
- Check if product of first N natural numbers is divisible by their sum in Python
- Print numbers with digits 0 and 1 only such that their sum is N in C Program.
- Find the number closest to n and divisible by m in C++
- Count pairs of numbers from 1 to N with Product divisible by their Sum in C++
- Find set of m-elements with difference of any two elements is divisible by k in C++
- Print array elements that are divisible by at-least one other in C++
- Add N digits to A such that it is divisible by B after each addition in C++?
- N digit numbers divisible by 5 formed from the M digits in C++
- Add N digits to A such that it is divisible by B after each addition?
- Find permutation of n which is divisible by 3 but not divisible by 6 in C++

Advertisements