天天看點

洛谷 -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的值
}