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)

#![allow(unused_imports, non_snake_case)]
use proconio::{
    input, fastout,
    marker::{Chars, Bytes, Usize1}
};

fn factorize(N: u64) -> Vec<(u64, usize)> {
    let mut X = N;
    let mut res = Vec::new();
    for i in 2..N {
        if i * i > N { break; }
        if X % i == 0 {
            let mut v = 0;
            while X % i == 0 {
                v += 1;
                X /= i;
            }
            res.push((i, v));
        }
    }
    if X > 1 {
        res.push((X, 1));
    }
    res
}

fn extended_euclidean(u: i64, v: i64) -> i64 {
    let mut r0 = u;
    let mut r1 = v;
    let mut s0 = 1;
    let mut s1 = 0;
    let mut t0 = 0;
    let mut t1 = 1;
    while r1 != 0 {
        let q = r0 / r1;
        let r = r0 - q * r1;
        let s = s0 - q * s1;
        let t = t0 - q * t1;
        r0 = r1;
        s0 = s1;
        t0 = t1;
        r1 = r;
        s1 = s;
        t1 = t;
    }
    // println!("{} * {} + {} * {} = {}", s0, u, t0, v, r0);
    if t0 < 0 {
        t0 + u
    } else {
        t0
    }
}

#[fastout]
fn main() {
    input!{
        N: u64
    }
    let mut out = vec![];
    for &(p, k) in &factorize(N * 2) {
        let mut v = 1;
        for _ in 0..k {
            v *= p;
        }
        out.push(v);
    }
    let mut ans = N * 2;
    let m = out.len();
    for bit in 0..(1 << m) {
        let mut x = 1;
        for i in 0..m {
            if (bit >> i) & 1 == 0 {
                x *= out[i];
            }
        }
        let y = N * 2 / x;
        let mut t = extended_euclidean(x as i64, y as i64) as u64;
        if t * y < 2 {
            t += x;
        }
        ans = std::cmp::min(ans, y*t-1);
    }
    println!("{}", ans);
}