题目链接:选数
题意很简单,给你n个数,从中选出k个数,问k个数的和为素数的情况有多少种,因为n的范围是20,所以很容易的想到深搜,然后只需要判断当前位置的数取还是不取就可以了,具体看代码
#include <bits/stdc++.h>
using namespace std;
int n,k,a[25],cot;
bool isprime(int s){
for(int i = 2;i*i <= s;i++){
if(s%i == 0) return false;
}
return true;
}
void dfs(int x,int y,int z){
if(y == k){
if(isprime(z)) cot++;
return ;
}
if(x == n+1) return ;
dfs(x+1,y,z);
dfs(x+1,y+1,z+a[x]);
}
int main(){
cin>>n>>k;
for(int i = 1;i <= n;i++)
cin>>a[i];
cot = 0;
dfs(1,0,0);
cout<<cot<<endl;
}