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(dead_code, unused_imports, deprecated)]
use std::cmp::{max, min, Reverse};
use std::collections::*;
use maplit::*;
use num::Integer;
use proconio::input;
use proconio::marker::*;
use proconio::fastout;

const INF : usize = 1000000007;

fn main() {
  input! {
    n: i128,
  };

  let mut res = vec![];
  for i in 1..=n {
    if i * i > 2 * n { break; }
    
    if (2 * n) % i == 0 {
      let j = (2 * n) / i;
      if let Some((k, _)) = chinese_rem(0, i, j - 1, j) {
        if k > 0 {
          res.push(k);
        }
      }
      if let Some((k, _)) = chinese_rem(0, j, i - 1, i) {
        if k > 0 {
          res.push(k);
        }
      }
    }
  }
  
  println!("{}", res.iter().min().unwrap());
}

fn ext_gcd(a: i128, b: i128, x: &mut i128, y: &mut i128) -> i128 {
  if b == 0 {
    *x = 1;
    *y = 0;
    a 
  } else {
    let d = ext_gcd(b, a % b, y, x);
    *y -= (a / b) * (*x);
    d
  }
}

fn chinese_rem(b1: i128, m1: i128, b2: i128, m2: i128) -> Option<(i128, i128)> {
  let mut x = 1i128;
  let mut y = 0i128;
  let d = ext_gcd(m1, m2, &mut x, &mut y);

  if (b2 - b1) % d != 0 {
    None
  } else {
    let m = m1 * (m2 / d);
    let t = ((b2 - b1) / d * x) % (m2 / d);
    let r = ((b1 + m1 * t) + m) % m;
    Some((r, m))
  }
}