合数分解质数之和较好的解法
算法思想,搜索+较强减枝.小于5000的数据,可于瞬间出解,且保证解的准确性,若无解则输出No answer
程序代码:
/* Author: SunKai E-mail: sunkai [at] msn [dot] com */ #include<stdio.h> #include<math.h> #include<string.h> #define SIZE 1000 int best[SIZE],lenbest; /*当前最好的序列及长度*/ int q[SIZE]; /*当前尝试*/ int x[SIZE]={2},lenx; /*质数表*/ int lenmax; int dfs(int now,int left,int count) { int i,j; int tmp; if(left==0) { if(count>lenbest) { memcpy(best,q,sizeof(best)); lenbest=count; } if(count==lenmax) return 1; return 0; } for(i=now;i<lenx;i++) { if(left<x[i]) return 0; tmp=left; for(j=i;j<lenx;j++) { tmp-=x[j]; if(tmp<0) break; } if(count+j-i<=lenbest) return 0; q[count]=x[i]; if(dfs(i+1,left-x[i],count+1)) return 1; } return 0; } int main(void) { int i,j,tmp; int n; while(scanf("%d",&n)!=EOF) { lenx=1; memset(best,0,sizeof(best)); lenbest=0; for(i=3;i<=n;i++) { tmp=sqrt(i); for(j=2;j<=tmp;j++) if(i%j==0) break; if(j>tmp) { x[lenx]=i; lenx++; } } tmp=0; lenmax=0; for(i=0;i<lenx;i++) { tmp+=x[i]; lenmax++; if(tmp>n) { lenmax--; break; } if(tmp==n) break; } dfs(0,n,0); for(i=0;i<lenbest;i++) printf("%4d ",best[i]); if(!lenbest) printf("No answer"); printf("\n"); } return 0; }
程序二,经过本帖在11楼前的讨论,对于程序进行了修改,使之解为元素个数最多且最大元素最小
程序代码:
#include<stdio.h> #include<math.h> #include<string.h> #define SIZE 1000 int best[SIZE],lenbest,great; /*当前最好的序列及长度*/ int q[SIZE]; /*当前尝试*/ int x[SIZE]={2},lenx; /*质数表*/ int lenmax; int dfs(int now,int left,int count) { int i,j; int tmp; if(left==0) { if(count>lenbest || (count==lenbest && q[count-1]<great)) { memcpy(best,q,sizeof(best)); lenbest=count; great=q[count-1]; } if(count==lenmax) return 0; return 0; } for(i=now;i<lenx;i++) { if(left<x[i]) return 0; tmp=left; if(x[i]>great) return 0; for(j=i;j<lenx;j++) { tmp-=x[j]; if(tmp<0) break; } if(count+j-i+1<=lenbest) return 0; q[count]=x[i]; dfs(i+1,left-x[i],count+1); } return 0; } int main(void) { int i,j,tmp; int n; while(scanf("%d",&n)!=EOF) { lenx=1; great=10000000; memset(best,0,sizeof(best)); lenbest=0; for(i=3;i<=n;i++) { tmp=sqrt(i); for(j=2;j<=tmp;j++) if(i%j==0) break; if(j>tmp) { x[lenx]=i; lenx++; } } tmp=0; lenmax=0; for(i=0;i<lenx;i++) { tmp+=x[i]; lenmax++; if(tmp>n) { lenmax--; break; } if(tmp==n) break; } dfs(0,n,0); for(i=0;i<lenbest;i++) printf("%4d ",best[i]); if(!lenbest) printf("No answer"); printf("\n"); } return 0; }
[[it] 本帖最后由 卧龙孔明 于 2008-4-12 17:45 编辑 [/it]]