The sum problem
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 23781 Accepted Submission(s): 7068
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]
思路:利用等差数列的性质 末项an=a1+(n-1)*d; n项和sn=(a1+an)*n/2=a1*n+n*(n-1)*d/2;
在本题中,d=1, sn=m; 即有m=a1*n+n*(n-1)/2;
假设首项是1,我们代入m=a1*n+n*(n-1)/2,则有n(n+1)=2m(n是项数的个数)。
所以有n*(n+1)=2m>n*n,即n<sqrt(2m); 也就是说项数最多的情况也只有sqrt(2m)。这也就是说,
假设M给的是10的9次方,最大的答案区间撑死也只有46000左右的长度。也就是2的10次的算术平方根。
(以上的'n'不是题目中的n,以上的'm'为题目中的m)
那么我们枚举1---sqrt(2m),枚举的是项数的个数(即数列区间长度);
m知道了,长度知道了,那么可以解出首项;(即解方程m=a1*n+n*(n-1)/2;)
又这个数列的每一项必定是个正整数,那么如果算出来的首项正好是个正整数,那么就是个答案,
区间就是【算出来的整数,整数+长度-1】输出即可。
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
int n,m;
while(cin>>n>>m,n||m)
{
double a1,flag;
for(int i=floor(sqrt(2*m));i>0;i--) //i是区间长度,即子数列项数个数
{
a1=(1.0*2*m/i-i+1)/2; //解方程求子数列首项
flag=a1-floor(a1);
if(flag==0&&a1<=m&&a1+i-1<=m)printf("[%.lf,%.lf]\n",a1,a1+i-1);
}
printf("\n");
}
return 0;
}