def fib_rec(a, b, p, q, count, m) if count == 0 return b % m elsif count.even? fib_rec(a, b, (p * p + q * q) % m, (2 * p * q + q * q) % m, count // 2, m) else fib_rec((b * q + a * q + a * p) % m, (b * p + a * q) % m, p, q, count - 1, m) end end def fib(n, m) fib_rec(1, 0, 0, 1, n, m) end def main n, m = read_line.split.map(&.to_u128) puts fib(n - 1, m) end main