Hdoj 2058
描述
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 contains multiple test cases. each case contains two integers N, M( 1 <= N, M <= 1000000000).input ends with N = M = 0.
输出
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.
样例输入
20 10
50 30
0 0
样例输出
[1,4]
[10,10]
[4,8]
[6,9]
[9,11]
[30,30]
思路
等差数列求和的变形。
\(S=\frac{(k+k+n-1)*n}{2}\)
\(2k=\frac{2s}{n}-n+1, n≤\sqrt{S}\)
枚举n然后算出k就好
代码
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
ll n, m;
while(~scanf("%lld %lld", &n, &m))
{
if(n + m == 0) break;
ll k, t;
for(t = sqrt(2 * m); t > 0; t--)
{
if(2 * m % t) continue;
ll r = 2 * m / t - t + 1;
if(r % 2) continue;
k = r >> 1;
printf("[%lld,%lld]\n", k, k + t - 1);
}
printf("\n");
}
return 0;
}