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: Accepted)

#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <cmath>
#include <iomanip>
#include <unordered_map>
#include <vector>
#include <string>

using ll = long long;

using namespace std;

vector<ll> factorize(ll n) {
    vector<ll> ans;
    for (ll i = 2; i * i <= n || i < 1000000; ++i) {
        ll d = 1;
        while (n % i == 0) {
            n /= i;
            d *= i;
        }
        if (d > 1) {
            ans.push_back(d);
        }
    }
    if (n > 1) {
        ans.push_back(n);
    }
    return ans;
}

ll gcd (ll a, ll b, ll & x, ll & y) {
    if (a == 0) {
        x = 0; y = 1;
        return b;
    }
    ll x1, y1;
    ll d = gcd (b%a, a, x1, y1);
    x = y1 - (b / a) * x1;
    y = x1;
    return d;
}
 
bool find_any_solution (ll a, ll b, ll c, ll & x0, ll & y0, ll & g) {
    g = gcd (abs(a), abs(b), x0, y0);
    if (c % g != 0)
        return false;
    x0 *= c / g;
    y0 *= c / g;
    if (a < 0)   x0 *= -1;
    if (b < 0)   y0 *= -1;
    return true;
}

void solve() {
    ll n;
    cin >> n;
    auto fact = factorize(2 * n);

    ll ans = n;

    for (int mask = 0; mask < (1 << fact.size()); ++mask) {
        ll a1 = 1, a2 = 1;
        for (int j = 0; j < fact.size(); ++j) {
            if (mask & (1 << j)) {
                a1 *= fact[j];
            } else {
                a2 *= fact[j];
            }
        }
        ll x0, y0;
        ll g = 1;
        find_any_solution(a2, -a1, 1, x0, y0, g);
        while (x0 <= 0 || y0 <= 0) {
            x0 += a1;
            y0 += a2;
        }
        while (x0 - a1 > 0 && y0 - a2 > 0) {
            x0 -= a1;
            y0 -= a2;
        }
        ans = min(ans, a1 * y0);
    }
    cout << ans << '\n';
}

int main() {
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
#endif
    solve();
}