hdoj 11页

hdoj #2058

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.

Simple Input

20 10
50 30
0 0

Simple Output

[1,4]
[10,10]

[4,8]
[6,9]
[9,11]
[30,30]

方法:等差求和公式的运用

Sn = n * a0 + (n * (n - 1) / 2) * d; n为项数,d为公差,a0为首项;
1+2+3+....+(2m)^1/2 > m 可由等差求和公式证明;所以最多就(2m)^1/2项;
代码如下:


#include <iostream>
#include <cmath>
using namespace std;
int main(){
	int n, m;
	while(cin>>n>>m && (n || m)){
		for(int i = sqrt(2 * m);i >= 1;i--){
			int a = (m - (i*(i-1))/2) / i;
			if((a * 2 + i - 1) * i == 2 * m)
				printf("[%d,%d]\n", a, a+i-1);
		}
		printf("\n");
	}
	return 0;
}
posted @ 2020-03-20 12:24  Codroc  阅读(164)  评论(0编辑  收藏  举报