已知 n 个整数 x1,x2,…,xn,以及一个整数 k(k<n)。从 n 个整数中任选 k 个整数相加,可分别得到一系列的和。例如当 n=4,k=3,4 个整数分别为 3,7,12,19 时,可得全部的组合与它们的和为:
3+7+12=22 3+7+19=29 7+12+19=38 3+12+19=34。
现在,要求你计算出和为素数共有多少种。
例如上例,只有一种的和为素数:3+7+19=29)。
键盘输入,格式为:
n , k (1<=n<=20,k<n)
x1,x2,…,xn (1<=xi<=5000000)
屏幕输出,格式为:
一个整数(满足条件的种数)。
4 3
3 7 12 19
//Serene #include<algorithm> #include<iostream> #include<cstring> #include<cstdlib> #include<cstdio> #include<cmath> using namespace std; const int maxn=20+5; int n,k,a[maxn],tot; bool ok(int x) { if(x<=1) return 0; int y=sqrt(x); for(int i=2;i<=y;++i) if(x%i==0) return 0; return 1; } void s(int pos,int f,int x) { if(f==k) { if(ok(x)) tot++; return; } if(pos>n) return; s(pos+1,f,x); s(pos+1,f+1,x+a[pos]); } int main() { cin>>n>>k; for(int i=1;i<=n;++i) cin>>a[i]; s(1,0,0); cout<<tot; return 0; }