The sum problem

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]

题目大意:给出两个数n和m;在不大于n的情况下给出一个闭区间,闭区间内的数加起来的和是m。当nm0时输入结束

关键点:用两层for循环的话会tle;网上搜了一下,都是用等差数列公式做的;
Sn=(a1+an)n/2;把i看做首项,j代表有多少项,故尾项就为i+j-1;因此(i+i+j-1)j/2=m;jj<=2m,把j从sqrt(2m)倒着枚举,求出对应的i值;再将i,j的值代入原式对比。
Code:

#include<iostream>
#include<math.h>
#include<cstdio>
#define N 1000000
using namespace std;
int main(){
	int n,m;
	while(cin>>n>>m&&n!=0&&m!=0){
		for(int j=sqrt(2*m);j>0;j--){
			int i=((2*m)/j+1-j)/2;
			if(m==((2*i+j-1)*j)/2) printf("[%d,%d]
",i,i+j-1);
		}
		cout<<endl;
	}
	return 0;
}
七月在野,八月在宇,九月在户,十月蟋蟀入我床下
原文地址:https://www.cnblogs.com/voids5/p/12695058.html