首页 > ACM题库 > HDU-杭电 > hdu 2058 The sum problem-数论-[解题报告]C++
2013
12-26

hdu 2058 The sum problem-数论-[解题报告]C++

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 contains multiple test cases. each case contains two integers N, M( 1 <= N, M <= 1000000000).input ends with N = M = 0.

输出:

Input contains multiple test cases. each case contains two integers N, M( 1 <= N, M <= 1000000000).input ends with N = M = 0.

样例输入:

20 10
50 30
0 0

样例输出:

[1,4]
[10,10]

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

hdu 2058 解题报告 – The sum problem

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2058


等差求和公式:

Sn=(a1+aN)*n/2
    =(a1+a1+d(n-1))*n/2
    =a1*n+d(n-1)*n/2;
因为此处公差d=1,所以Sn=a1*n+(n-1)*n/2,当从第一项开始算起时(因本题首项为1,即a1=1时),Sn=M时的项的个数n最多;
a1=1,现在又可化简为Sn=n+(n-1)*n/2=(n+1)n/2;
由题意得M=Sn,N为项的个数,则N<=n(max)=sqrt(Sn*2)=sqrt(M*2);
因此原式M=Sn =a1*n+(n-1)n/2=a1*N+(N-1)N/2,可得a1*N=M-(N-1)N/2;
数据都已经全了,现在只要遍历n(max)以内项数中,Sn=M的个数即可。
那么如何判断Sn=M呢?也就是判断a1*N=Sn-(N-1)N/2;得到的a1*N这个数能否被N整除,因为整除的话,说明首项存在于序列

#include<stdio.h>
#include<math.h>
int main(){
    int N,M;


    while(scanf("%d%d",&N,&M),N||M){
        int len = (int)sqrt(M*2.0);
        int a1_len=0;//首项a1与len的乘积
        
        for (;len>0;len--){
            a1_len=M-(len-1)*len/2;//a1*N=M-(N+1)N/2;
            if(a1_len%len==0){
                printf("[%d,%d]\n",a1_len/len,a1_len/len+len-1);
            }
        }
        puts("");
    }


    return 0;
}

解题转自:http://blog.csdn.net/lianqi15571/article/details/8835270