天天看点

洛谷 -P1147 连续自然数和 (数论)

题目传送

题意:

洛谷 -P1147 连续自然数和 (数论)

思路 :

首先我们知道连续的自然的和的公式为:

(L+R) * (R-L+1)/2

根据题意我们得出:

(L+R) * (R-L+1) == 2*n

我们假设现在k1 * k2 == 2*n,且假设k2 > k1

那么k2 = (L+R),k1 = (R-L+1),根据这俩个方程得出:

L = (k2 - k1 + 1) / 2

R = (k1 + k2 - 1) / 2

那么L,R必定为整数,所以又得出,k1,k2肯定一奇数一偶数

那么我们现在就枚举k1来获得k2,再来判断成立条件

此方法把时间复杂度降到了O(sqrt(2*n))

但是这个题的数据较小可以暴力过

AC代码

#include <bits/stdc++.h>
inline long long read(){char c = getchar();long long x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) (x)&(-x)
const int N = 5e3 + 10;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const int mod = 1e9+7;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
signed main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    //    freopen("input.txt","r",stdin);
    //    freopen("output.txt","w",stdout);
    ll n;
    cin >> n;
    for(ll k1 = sqrt(2*n);k1 > 1;k1--)
        if(2*n % k1 == 0 && (k1 + 2*n/k1) % 2 == 1)//判断成立的条件
            cout << ((2*n/k1)-k1+1)/2 << " " << (2*n/k1+k1-1)/2 << endl;
            //(2*n)/k1为k2的值
}