hdu 2058 The Sum Problem

题解:

  数学题,等差数列的运用。Sn = (a1+an) * n / 2 = (a1 + a1 + (n - 1) * d)*n/2。

解题公式变形:(a+a+len)*(len+1)/2 = m => a = m/(len+1)-len/2 (m是已知条件,len的最大值为√(2*m)

代码如下:

#include <stdio.h>
#include <math.h>

int main()
{
    int n, m, a, len;
    while (scanf("%d%d", &n, &m) && (n || m))
    {
        len = (int)sqrt(2*m);
        while (len--)
        {
            a = m / (len + 1) - len / 2;
            if ((2*a+len) * (len+1) / 2 == m)
                printf("[%d,%d]\n", a, a+len);
        }
        printf("\n");
    }
    return 0;
}

 

posted on 2013-01-26 14:43  zm001  阅读(405)  评论(0编辑  收藏  举报