实例四十一:连续整数和问题
问题描述:
给定一个整数 x ,求出所有连续的且和为 x 的正整数。比如对于整数 27 ,结果为 2~7 、8~10、13、和14,因为这些连续整数的和都是 27。
Given an integer x , find all consecutive positive integers with a sum of x. For example, for the integer 27, the result is 2~7, 8~10, 13, and 14, because the sum of these consecutive integers is 27.
注意:并不是所有整数都有结果,例如不存在连续的整数和为 16。
Note: Not all integers have a result, such as the absence of consecutive integer sums and 16.
算法思路:
(1)从 1 开始计算连续的整数和为 sum,直到 sum 不小于 x 为止;
(2)在第 i 步,如果 sum=i+(i+1)+…+n 比 x 大,则可连续去掉连加最左端的数 i ,i+1,…进行探测,如果 sum 比 x 小,在连加的右端加上一个数 (n+1);
(3)如果和 sum=i+(i+1)+…+n 等于 x ,则 i+(i+1)+…+n 为一组多解,输出该解,并将连加的右端加上 (n+1);
(4)重复(2)、(3)步,直到 n 大于 x/2+1 为止。
(1) Calculate the continuous integer sum from 1 to 1 until sum is not less than x;
(2) In step i, if sum=i+(i+1)+…+n is larger than x, then the leftmost number i, i+1, … can be continuously removed to detect if Sum is smaller than x, and a number (n+1) is added to the right end of the continuation;
(3) If sum=i+(i+1)+…+n is equal to x, then i+(i+1)+…+n is a set of multiple solutions, output the solution, and add Add (n+1) to the right end;
(4) Repeat steps (2) and (3) until n is greater than x/2+1.
//实例四十一:连续整数和问题 C++程序示范
#include <iostream>
using namespace std;
int main()
{
int x,num,pResult,i=1,result=0;
cout<<"INPUT A NUMBER:\n";
cin>>x;
num=x/2+2; //
int sum=0;
for(int n=i;n<=num;)
{
pResult = x - sum;
if(pResult>0)
sum = sum+n++;
if(pResult<0)
sum = sum-i++;
if(pResult==0)
{
for(int j=i;j<n;j++)
cout<<j<<"";
result++;
cout<<endl;
break;
}
}
cout<<"RESULT:"<<result<<"\n";
return 0;
}