51nod 1138 连续整数的和(数学)

来源:互联网 发布:手机淘宝商家注册流程 编辑:程序博客网 时间:2024/06/06 00:18

题意:给出一个正整数N,将N写为若干个连续数字和的形式(长度 >= 2)。例如N = 15,可以写为1 + 2 + 3 + 4 + 5,也可以写为4 + 5 + 6,或7 + 8。如果不能写为若干个连续整数的和,则输出No Solution。(N<=1e9)


思路:我们知道等差数列求和公式为首项加末项再乘以项数除以2,公差为1的可以假如首项是a,则可以写成(a+a+n-1)*n/2

--->(2a+n-1)*n == 2N, 左边肯定大于n^2,所以只需要枚举n从2到sqrt(2N) 再判断是否存在a就可以了,复杂度O(sqrt(n))


代码:

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>using namespace std;typedef long long ll;const int maxn = 1e4+5;int dp[maxn], a[maxn];int main(void){    int n;    while(cin >> n)    {        n = n*2;        bool have = 0;        for(int i = sqrt(n); i >= 2; i--)        {            if(n%i == 0 && (n/i-(i-1))%2 == 0)            {                printf("%d\n", (n/i-(i-1))/2);                have = 1;            }        }        if(!have) puts("No Solution");    }    return 0;}




1 0
原创粉丝点击