鱼C论坛

 找回密码
 立即注册
查看: 2897|回复: 0

[技术交流] 正整数分解的算法问题

[复制链接]
发表于 2011-9-26 22:36:08 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 yipwing 于 2011-9-26 22:36 编辑

将一个正整数分解为多个正整数(相加)之和,其中前一个加数不小于后一个加数,列出每种可能的加数组合中的所有加数。而且加数不能重复;限制几个数相加,限制最小数,最大数,要求把结果输出到output.txt

例: 分解数为9,只能是3个数相加,最小数1,最大数5. 要求以传递参数方式..
结果:
9
5+3+1
4+3+2

这个是我的代码,希望各位大牛们给个更好的算法。。。小弟在这里先谢了。。。
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. void filewrite(int* a,int top2)
  5. {
  6.     int i;
  7.     FILE *pFile;

  8.     pFile=fopen("output.txt","a+");
  9.     for(i=0; i<top2-1; i++)
  10.     {
  11.         fprintf(pFile,"%d+",a[i]);
  12.     }
  13.     fprintf(pFile,"%d\n",a[i]);
  14.     fclose(pFile);
  15.     return;
  16. }

  17. void partion(int top1,int top2,int limit,int *a,int count,int min,int max)
  18. {
  19.     int i=0;
  20.     if(top1==0)              //如果s1中已无元素,则划分完毕,输出
  21.     {
  22.         if(limit==count)     //限制显示结果为输入的个数
  23.         filewrite(a,top2);
  24.     }
  25.     else
  26.     {
  27.         for(i=top1; i>=1; i--)
  28.         {
  29.             if(top2==0||i<=a[top2-1])
  30.             {
  31.                 a[top2]=i;                  //从s1中取出的1的个数压入s2
  32.                 if(a[top2]!=a[top2-1] && a[top2] <= max && a[top2] >= min )         //比较是否和之前的值一样,如果一样就跳过递归,重新调用一次递归
  33.                 {
  34.                     partion(top1-i,top2+1,limit,a,count+1,min,max);   //对s1中剩下的1再次进行取栈操作
  35.                 }
  36.             }
  37.         }
  38.     }
  39. }

  40. int Param;
  41. int main(int argc,char ** argv)
  42. {
  43.     int top1,top2,limit,count,min,max; //
  44.     int *a;
  45.     FILE *pFile;
  46.     pFile= fopen("output.txt","w");
  47.     if(pFile!=NULL)
  48.         fclose(pFile);

  49.     top1=atoi(argv[1]); // 分解数
  50.     limit=atoi(argv[2]); // 限制个数
  51.     min=atoi(argv[3]); // 最小数
  52.     max=atoi(argv[4]); // 最大数
  53.     Param=1;
  54.     while(Param--==1&&top1>=0)
  55.     {
  56.         top2=0;
  57.         count=0;
  58.         a=(int *)malloc(top1*sizeof(int));
  59.         printf("--------------Start--------------\n");
  60.         partion(top1,top2,limit,a,count,min,max);

  61.     }
  62.     return 0;
  63. }
复制代码




小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-13 10:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表