计算 C++ 中满足给定条件的子集
给定一个数字数组和一个整数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整除的元素,然后返回2count-1作为所需的子集数。
取一个整数数组arr[]。
以x作为输入。
函数count(intarr[],intn,intx)接受一个数组和x并返回满足给定条件的子集计数。
如果x是1则它除以所有元素,所以返回
示例
#include#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: "< 输出结果 如果我们运行上面的代码,它将生成以下输出-
Count of sub−sets that satisfy the given condition are: 7