lib C fun strtoll(s : UInt8*, p : UInt8**, b : Int32) : Int64 end class String def to_i64 C.strtoll(self, nil, 10) end end def index_to_perm(n, x) remain = (1..n).to_a (1..n).map { |i| f = (1..n - i).reduce(1i64) { |acc, i| acc*i } i = x // f x -= i * f remain.delete_at(i) } end def reverse_perm(n, a) index = [-1] * n (0...n).each do |i| index[a[i] - 1] = i + 1 end index end def perm_to_index(n, a) remain = (1..n).to_a (1..n).sum { |i| f = (1..n - i).reduce(1i64) { |acc, i| acc*i } i = remain.index(a[i - 1]).not_nil! remain.delete_at(i) f * i } end x, n = read_line.split.map(&.to_i64) a = index_to_perm(n, x) b = reverse_perm(n, a) ans = perm_to_index(n, b) puts ans