将一个正整数n分解成m个连续自然数的和
如:
6 = 1+2+3
9 = 2+3+4
9 = 4+5
#include<stdio.h>
void getSeqSum(int n)
{
int begin, i,j, sum;
begin = 1;
sum = begin;
for (i = 1; i <= (n+1)/2; )
{
//remove the minmum
if (sum > n)
{
sum -= begin;
++begin;
}
else
{
//output the result, remove the minmum
if (sum == n)
{
printf("%d = ", n);
for (j = begin; j < i; ++j)
{
printf("%d + ", j);
}
printf("%d\n", j);
sum -= begin;
begin++;
}
++i;
sum += i;
}
}
}
int main(void)
{
printf("please input the number:\n");
int n;
scanf("%d", &n);
getSeqSum(n);
}
________________________________________________________
please input the number:
6
6 = 1 + 2 + 3
please input the number:
9
9 = 2 + 3 + 4
9 = 4 + 5
please input the number:
15
15 = 1 + 2 + 3 + 4 + 5
15 = 4 + 5 + 6
15 = 7 + 8