ในปัญหานี้ เราได้รับอาร์เรย์ขององค์ประกอบ N และจำเป็นต้องส่งคืนผลรวมขององค์ประกอบทั้งหมดหารด้วยจำนวนเต็ม M.
Input : array = {4, 7, 3} ; M = 3
Output : 5+4+3 ; 5+4-3 เพื่อแก้ปัญหานี้ เราจำเป็นต้องรู้แนวคิดของชุดกำลังที่สามารถใช้ในการหาผลรวมที่เป็นไปได้ทั้งหมดที่ได้รับ จากผลรวมนี้ให้พิมพ์ทั้งหมดที่หารด้วย M.
อัลกอริทึม
Step 1: Iterate overall combinations of ‘+’ and ‘-’ using power set. Step 2: If the sum combination is divisible by M, print them with signs.
ตัวอย่าง
#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;
} ผลลัพธ์
ผลรวมหารด้วย n −
. ลงตัว- 4 + 7 - 3 - 4 + 7 + 3 + 4 - 7 - 3 + 4 - 7 + 3