标签:
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]
思路
((首项+末项)*项数)/2=m以及 末项=首项+项数-1联立方程组可以得到一个关于左区间项,项数,M的一个方程。
假设首项是1,我们代入,很容易得到n(n+1)=2m这个公式(n是项数)。 这里可以把n+1看成n,n^2=2m,n=sqrt(2m); 也就是说项数最多的情况也只有sqrt(2m)。大大减小了枚举长度。另外,(a+a+len)*(len+1)/2 = m => a = m/(len+1)-len/2
#include<stdio.h> #include<math.h> int main() { int N,M,val,len; while (~scanf("%d%d",&N,&M) && N && M) { len = (int)sqrt(2*M); while (len--) { val = M / (len + 1) - len /2; if ((2*val+len) * (len+1) / 2 == M) printf("[%d,%d]\n", val, val+len); } printf("\n"); } return 0; }
标签:
原文地址:http://www.cnblogs.com/zzy19961112/p/5866993.html