任何一个大于1的自然数n,总可以拆分成若干个小于n的自然数之和。
发布网友
发布时间:2024-09-26 23:57
我来回答
共1个回答
热心网友
时间:2024-11-16 13:23
# include <stdio.h>
# include <stdlib.h>
# include <malloc.h>
//int n;
int total = 0;
int n;
int * p = (int *)malloc(n * sizeof(int));
//int p[1024]={0};
void chf (int a, int m);
int main (void)
{
//int n;
//int * p = (int *)malloc(n * sizeof(int));
printf ("请输入一个数:");
scanf("%d", &n);
chf (n, 1);
printf("共有%d种方式拆分%d\n", total, n);
return 0;
}
void chf (int a, int m)
{
int rest, j, i;
for (i = 1; i <= a; i++)//i <= a;否则rest==0永远不成立;
{
if (i >= p[m -1])
{
p[m] = i;
rest = a - i;
if (rest == 0 && m > 1)
{
total++;
printf("第%d种:", total);
for (j = 1; j < m; j++)
{
printf("%d+", p[j]);
}
printf("%d\n", p[m]);
}
else
{
chf(rest, m +1);
}
p[m] = 0;
}
}
}