题目描述:一个正整数有可能可以被表示为 n(n>=2) 个连续正整数之和,如: 15=1+2+3+4+5 15=4+5+6 15=7+8 请编写程序,根据输入的任何一个正整数,找出符合这种要求的所有连续正整数序列。(2005年百度之星第一题)
#include <iostream>
using namespace std;
void display( int num, int min, int max)
{
cout << num << '=';
if ( min > 0 )
{
cout << min << '+';
}
for ( int k = min + 1; k < max; ++k )
{
cout << k << '+';
}
cout << max << endl;
}
void detach( int num )
{
bool detachable = false;
int half = num / 2;
for ( int i = 2; i <= half; ++i )
{
if ( 0 == num % i )
{
int j = num / i;
if ( 1 == j % 2 )
{
int hj = j / 2;
if ( i >= hj )
{
detachable = true;
display( num, i - hj, i + hj );
}
}
if ( 1 == i % 2 )
{
int hi = i / 2;
if ( hi == j || hi + 1 == j ) /* prevent duplicate */
{
continue;
}
if ( hi >= j - 1 )
{
detachable = true;
display( num, hi - j + 1, hi + j );
}
}
}
}
if ( num > 1 && 1 == num % 2 )
{
detachable = true;
display( num, num / 2, num / 2 + 1 );
}
if ( !detachable )
{
cout << "none" << endl;
}
}
int main()
{
int num = 0;
while (cin >> num)
{
detach(num);
}
return(0);
}
http://wenku.baidu.com/view/81dfec47be1e650e52ea99e0.html中的方法:
#include <cstdio>
int sum(int start, int end)
{
int total = 0;
while (start <= end)
{
total += start;
start += 1;
}
return(total);
}
void show(int start, int end, int sum)
{
if (start >= end)
{
return;
}
printf("%d = %d", sum, start);
while (start != end)
{
printf(" + %d", ++start);
}
printf("\n");
}
void detach(int n)
{
int low = 1;
int high = low + 1;
while (low < high)
{
int total = sum(low, high);
if (total < n)
{
high += 1;
}
else if (total > n)
{
low += 1;
}
else
{
show(low, high, n);
low += 1;
}
}
}
int main(int argc, char * argv[])
{
int num = 0;
while (scanf("%d", &num) > 0)
{
detach(num);
}
return(0);
}