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