class MatrixDoubling: """行列累乗(A**n)を繰り返し二乗法によって解く。""" def __init__(self, rig, A, n): # 二項演算を定義 self.add = rig.add self.zero = rig.zero self.mul = rig.mul self.one = rig.one # 単位行列Eを生成 self.E = [[self.zero] * len(A) for i in range(len(A))] for i in range(len(A)): self.E[i][i] = self.one # self.powA = [A**1, A**2, A**4, A**8, ... ] を生成 self.log_size = n.bit_length() self.powA = [A] while len(self.powA) < self.log_size: self.powA.append(self._matrix_mul(self.powA[-1], self.powA[-1])) def _matrix_mul(self, A, B): """行列Aと行列Bの積を求める。""" C = [[self.zero] * len(B[0]) for i in range(len(A))] for i in range(len(A)): for k in range(len(B)): for j in range(len(B[0])): C[i][j] = self.add(C[i][j], self.mul(A[i][k], B[k][j])) return C def solve(self, k): """A**k を求める""" B = self.E[:] for i in range(k.bit_length()): if (k >> i) & 1: B = self._matrix_mul(self.powA[i], B) return B class SemiRing: def __init__(self, add, zero, mul, one): self.add = add self.zero = zero self.mul = mul self.one = one n, MOD = map(int, input().split()) add = lambda a, b: (a + b) % MOD zero = 0 mul = lambda a, b: a * b % MOD one = 1 rig = SemiRing(add, zero, mul, one) matrix = [[1, 1], [1, 0]] md = MatrixDoubling(rig, matrix, n) ans_matrix = md.solve(n) print(ans_matrix[-1][-1])