求正整数n的不同划分个数C语言实现
#include <stdio.h>
int mark[200];
int n;
FILE *fp;
int split(int n ,int m){
if(m==1){
return 1;
}
if(m>n){
return split(n,n);
}
if(m==n){
return split(n,m-1)+1;
}
return split(n,m-1)+ split(n-m,m);
}
void print(int sum, int k, int prio)
{
if (sum > n)
return;
if (sum == n)
{
int i;
for (i = 0; i < k - 1; i++)
{
fprintf(fp,"%d+",mark[i]);
printf("%d+",mark[i]);
}
fprintf(fp,"%d\n",mark[i]);
printf("%d\n",mark[i]);
}
else {
for (int j = prio; j > 0; j--)
{
mark[k] = j;
sum += j;
print(sum, k + 1, j);
sum -= j;
}
}
}
int main(){
int m,k;
printf("请输入需要划分的数字: ");
scanf("%d",&n);
printf("请输入最大划分数: ");
scanf("%d",&m);
k=split(n,m);
if( (fp=fopen("demo.txt","w+")) == NULL ){
puts("Fail to open file!");
}
printf("数字是:%d\n",n);
fprintf(fp,"数字是:%d\n",n);
print(0,0,n);
fprintf(fp,"\n");
printf("\n");
printf("总共%d种划分方法",k);
fprintf(fp,"总共%d种划分方法",k);
fclose(fp);
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e31241c09ad8d0fb330238fcbf375573.png#pic_center)