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 Rust (1.42.0) (judge verdict: Accepted)

use proconio::*;
use proconio::marker::*;

// k * (k + 1) / 2 == 0 (mod n)
// n % 2 != 0 なら
// k * (k + 1) == 0 (mod n)
// n % 2 == 0 なら
// k * (k + 1) == 0 (mod 2 * n)
// k を約数dで決めうち
// a * d + 1 == 0 (mod n / d)
//
// を満たすaを求める

fn factorize(n: u128) -> Vec<(u128, u128)> {
    let mut f = vec![];
    let mut n = n;
    for i in 2.. {
        if i * i > n {
            break;
        }
        let mut c = 0;
        while n % i == 0 {
            n /= i;
            c += 1;
        }
        if c > 0 {
            f.push((i, c));
        }
    }
    if n > 1 {
        f.push((n, 1));
    }
    f
}

fn gcd(a: u128, b: u128) -> u128 {
    if b == 0 {
        a
    } else {
        gcd(b, a % b)
    }
}

fn mod_pow(r: u128, n: u128, m: u128) -> u128 {
    let mut t = 1;
    let mut s = r;
    let mut n = n;
    while n > 0 {
        if n & 1 == 1 {
            t = t * s % m;
        }
        s = s * s % m;
        n >>= 1;
    }
    t
}

#[fastout]
fn run() {
    input! {
        n: u128,
    }
    let m = if n % 2 == 0 {
        2 * n
    } else {
        n
    };
    let p = factorize(m);
    let mut ans = m;
    for bit in 0..(1 << p.len()) {
        let mut x = 1;
        let mut y = 1;
        let mut z = 1;
        for (i, &(p, a)) in p.iter().enumerate() {
            if bit >> i & 1 == 1 {
                x *= p.pow(a as u32);
            } else {
                y *= p.pow(a as u32);
                z *= (p - 1) * p.pow((a - 1) as u32);
            }
        }
        if y == 1 {
            ans = std::cmp::min(ans, x);
        } else {
            let ix = mod_pow(x, z - 1, y);
            assert!(ix * x % y == 1, "{} {} {}", x, y, x * ix % y);
            let a = ix * (y - 1) % y;
            ans = std::cmp::min(ans, a * x);
        }
    }
    println!("{}", ans);
}

fn main() {
    run();
}