กำหนดอาร์เรย์ของตัวเลขและจำนวนเต็ม x เป็นอินพุต เป้าหมายคือการหาชุดย่อยทั้งหมดของ arr[] ที่แต่ละองค์ประกอบของชุดนั้นและผลรวมของชุดย่อยทั้งหมดหารด้วย x ลงตัว
ตัวอย่าง
อินพุต
arr[] = {1,2,3,4,5,6} x=3 ผลลัพธ์
Count of subsets that satisfy the given condition :3
คำอธิบาย
The subsets will be: [3], [6], [3,6]
อินพุต
arr[] = {1,2,3,4,5,6} x=4 ผลลัพธ์
Count of subsets that satisfy the given condition :1
คำอธิบาย
The subsets will be: [4]
แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้ −
ในวิธีนี้เราจะนับองค์ประกอบของ arr[] ที่หารด้วย x ลงตัวแล้วจึงคืนค่า 2 count -1 ตามจำนวนชุดย่อยที่ต้องการ
-
ใช้อาร์เรย์จำนวนเต็ม arr[].
-
รับ x เป็นอินพุต
-
ฟังก์ชั่น count(int arr[], int n, int x) รับอาร์เรย์และ x และคืนค่าจำนวนชุดย่อยที่ตรงตามเงื่อนไขที่กำหนด
-
ถ้า x เป็น 1 มันจะแบ่งองค์ประกอบทั้งหมด ให้กลับ
ตัวอย่าง
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int sub_sets(int arr[], int size, int val){
int count = 0;
if (val == 1){
count = pow(2, size) − 1;
return count;
}
for (int i = 0; i < size; i++){
if (arr[i] % val == 0){
count++;
}
}
count = pow(2, count) − 1;
return count;
}
int main(){
int arr[] = { 4, 6, 1, 3, 8, 10, 12 }, val = 4;
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"Count of sub−sets that satisfy the given condition are: "<<sub_sets(arr, size, val);
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
Count of sub−sets that satisfy the given condition are: 7