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 Ruby (2.7.1) (judge verdict: Wrong Answer)

require 'prime'

def extgcd(a, b)
  if b.zero?
    [1, 0, a]
  else
    x, y, d = extgcd(b, a % b)

    [y, x - (a / b) * y, d]
  end
end

N = gets.to_i

if N.prime?
  if N == 2
    puts 3
  else
    puts N - 1
  end
else
  primes = (2 * N).prime_division
  values = primes.map { |e, cnt| e ** cnt }
  cnt = primes.size
  ans = Float::INFINITY
  min_val = Float::INFINITY

  (1 << cnt).times do |mask|
    a = 1
    b = 1

    cnt.times do |i|
      if mask[i] == 0
        a *= values[i]
      else
        b *= values[i]
      end
    end

    x, y, _ = extgcd(a, b)
    s = (a * x.abs) * (b * y.abs)

    if s > 0 && min_val > s
      min_val = s
      v = [a * x.abs, b * y.abs].min
      ans = v 
    end
  end

  puts ans
end