Problem:
Score : 600 points

Problem Statement

Given is an integer N.
Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N.
It can be proved that such a positive integer k always exists.

Constraints

1 \leq N \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer in a line.

Sample Input 1

11

Sample Output 1

10

1+2+\cdots+10=55 holds and 55 is indeed a multple of N=11.
There are no positive integers k \leq 9 that satisfy the condition, so the answer is k = 10.

Sample Input 2

20200920

Sample Output 2

1100144

Solution in C++ (GCC 9.2.1) (judge verdict: Time Limit Exceeded)

#include<bits/stdc++.h>
#define rep(i,n) for ( int i=0; i< (n); ++i )
using namespace std;
using ll = long long;
using P = pair<int,int>;

// k(k+1)/2 = mN
//k(k+1) = k*k1 = 2mN => mN
//k+1 = mN/k = m'x q => k+1%q = 0
//k = mN/(k+1) = m''x q' => k%q' = 0
// k or k+1 ~ x2N
//(k, k+1 is independent)

// search max divisor of all #

ll gcd( ll m, ll n ){ // m/n
    if( n==0 ) return m;
    return gcd( n, m%n);
}

ll min_ll(ll a,ll b){
    if(a>b) return b;
    return a;
}

ll bst( ll n1, ll n2, ll N ){
    if( n2 - n1 == 1 ){
        ll ans0 = N;
        ll q = N/gcd(N,n1);
        if( (n1+1)%q == 0 ) ans0 = min_ll(ans0,n1);
        if( n1>1 and (n1-1)%q == 0 )  ans0 = min_ll(ans0,n1-1);
        return ans0;
    }
    ll piv = (n1+n2)/2;
    ll ans1 = bst(n1,piv,N);
    ll ans2 = bst(piv,n2,N);
    if( ans1 < ans2 ) return ans1;
    return ans2;
}

int main(){
    ll N;
    cin >> N;
    cout << bst( 1, 2*N, 2*N ) << endl;
    return 0;
}