Description
素数,又称质数,是指除 1 和其自身之外,没有其他约数的正整数。
例如 2、 3、 5、 13 都是质数,而 4、 9 、 12、 18 则不是。
虽然素数不能分解成除 1 和其自身之外整数的乘积,但却可以分解成更多素数的和。
你需要编程求出一个正整数最多能分解成多少个互不相同的素数的和。
例如, 21 = 2 + 19 是 21 的合法分解方法。
21 = 2 + 3 + 5 + 11 则是分解为最多素数的方法。
Format
Input
n (10 ≤ n ≤ 200)。
Output
最多能分解成多少个不同的素数
Samples
输入数据 1
21
Copy
输出数据 1
4
#include<bits/stdc++.h>
using namespace std;
int n;
int tot=0;
int aa[100000];
int ans;
int dd(int x) {
if(x==1)
return false;
if(x==2)
return true;
else if(x%2==0)
return false;
else {
int k=sqrt(x)+1;
for(int i=2; i<=k; i++) {
if(x%i==0)
return false;
}
return true;
}
return true;
}
void dfs(int dep ,int s,int pre) {
if(s==n) {
if(pre>ans) {
ans=pre;
}
return;
}
if(s>n||dep==tot+1)
return;
dfs(dep+1,s+aa[dep],pre+1);
dfs(dep+1,s,pre);
}
int main() {
cin>>n;
for(int i=2; i<=n; i++) {
if(dd(i)) {
aa[++tot]=i;
}
}
dfs(1,0,0);
cout<<ans;
return 0;
}
dfs一遍就行了,注意要找从什么时候开始。