#include<bits/stdc++.h>
using namespace std;
int n,k,c;
int a[5000005],ans[5000005];
bool prime(int num){//Is the number prime?
for(int i=2;i<num;i++){
if(num%i==0) return false;
}
return true;
}
void dfs(int step){
for(int i=1;i<=n;i++){
if(i>ans[step-1]){//Is the combination not repeated?
ans[step]=i;
if(step==k){//Is every space in the combination filled?
long long int cnt=0;
for(int j=1;j<=k;j++) cnt+=a[ans[j]];//calculating the sum
if(prime(cnt)) c++;//Is the sum prime?
}else dfs(step+1);//Move onto filling in the next space
}
}
}
int main(){
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];//input
dfs(1);
cout<<c;//output
return 0;
}
洛谷:P1036 [NOIP2002 普及组] 选数
最新推荐文章于 2024-07-19 15:45:46 发布
这篇文章介绍了一个C++程序,通过递归函数dfs计算一个整数数组中所有非重复组合的和,如果这些和是质数,则计数器c增加。主要涉及了数组操作、递归和质数判断。
摘要由CSDN通过智能技术生成