Problem Description
Given a sequence 1,2,3,……N, your job is to calculate all the possible sub-sequences that the sum of the sub-sequence is M.
Input
Input contains multiple test cases. each case contains two integers N, M( 1 <= N, M <= 1000000000).input ends with N = M = 0.
Output
For each test case, print all the possible sub-sequence that its sum is M.The format is show in the sample below.print a blank line after each test case.
Sample Input
20 10
50 30
0 0
Sample Output
[1,4]
[10,10]
[4,8]
[6,9]
[9,11]
[30,30]
解题思路:
这个题输入的数据可以很大,所以最简单粗暴的方法就不能用了,会timeout。
所以这个题可以换一个思路来做,首先需要知道一个数学知识:
所以和为m的元素的个数最多不超过 2m−−−√ 2 m 个,最少有 1 个。
接下来就可以用for循环,通过序列元素的个数来进行计算。
而这个计算需要用到等差数列求和公式:
a1 a 1 为首项,n为项数,d为公差,那么求首项的变形公式为:
通过上式即可求出首项 a1 a 1 ,那么最后一项就是 a1+n−1 a 1 + n − 1 ,即 [a1,a1+n−1] [ a 1 , a 1 + n − 1 ] .
代码:
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
long long n,m,a;
while(cin>>n>>m && n||m)
{
for(int i=sqrt(2*m); i>0; i--)
{
a=m/i-(i-1)/2;
//需检查i是否为整数。
if(a*i+i*(i-1)/2==m)
cout<<'['<<a<<','<<a+i-1<<']'<<endl;
}
cout<<endl;
}
}