
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 Combinations of N Elements with Sign Changes for Divisibility 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
Advertisements