HDOJ-2058

The sum problem

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 21744    Accepted Submission(s): 6391


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]
 
[4,8]
[6,9]
[9,11]
[30,30]
 

本题题意:

输入两个数n,m,n代表数列为从1~n的等比为1的等比数列,求其中连续哪几个数的和为m,并输出。

运用等差数列的求和公式就能很好的解决这个问题。下面重申一下等差数列的求和公式:

      formula    

附AC代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>//包含开根函数sqrt() 
 4 
 5 using namespace std;
 6 
 7 int main(){
 8     int n,m;
 9     while(~scanf("%d %d",&n,&m)&&m||n){
10         for(int i=sqrt(2*m);i>=1;i--){//1连加到sqrt(2*m) > m 
11             int a=(m-(i*(i-1))/2)/i;//等差求和公式推出 
12             if(m==a*i+(i*(i-1))/2)
13             printf("[%d,%d]
",a,a+i-1);
14         }
15         printf("
");//注意每组数据空一行 
16     }
17     return 0;
18 }
原文地址:https://www.cnblogs.com/Kiven5197/p/5475496.html