The sum 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]
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]
[6,9]
[9,11]
[30,30]
解题思路:
一看到N,M的范围就知道不能直接暴力,于是想到等差数列。(a+1,a+2。。。a+n)
即a*n+n(n+1)/2==m,即n*n<m;所以枚举 1-sqrt(2*m);如果a*n+n(n+1)/2==m成立即打印,注意枚举顺序从sqrt(2*m)到1。。。因为这个wa了一次。。。
ac代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
ll n,m,t;
while(~scanf("%lld%lld",&n,&m)){
if(m==0&&n==0) break;
ll t=sqrt(m*2.0);
for(ll i=t;i>=1;i--){
if((m-i*(i+1)/2)%i==0){
ll a=(m-i*(i+1)/2)/i;
printf("[%lld,%lld]\n",a+1,a+i);
}
}
printf("\n");
}
return 0;
}