#include using namespace std; using ll = __int128_t; ll N, M; struct Matrix { Matrix() { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { table[i][j] = 0; } } } static Matrix Unit() { Matrix ans; ans.table[0][0] = 1; ans.table[1][1] = 1; return ans; } Matrix operator*(const Matrix& mat) const { Matrix ans; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { ans.table[i][j] += (table[i][k] * mat.table[k][j]) % M; ans.table[i][j] %= M; } } } return ans; } array, 2> table; }; ll mul(const ll p, const ll n, const ll mod) //p*n の mod { if (n == 0) { return 0; } if (n % 2 == 1) { return (mul(p, n - 1, mod) + p) % mod; } else { const ll pp = mul(p, n / 2, mod); return (pp + pp) % mod; } } ll power(const ll n, const ll mod) { if (n == 0) { return 1; } if (n % 2 == 1) { return (power(n - 1, mod) * 2) % mod; } else { const ll pp = power(n / 2, mod); return mul(pp, pp, mod); } } Matrix power(const Matrix& mat, const ll n) { if (n == 0) { return Matrix::Unit(); } if (n % 2 == 1) { return power(mat, n - 1) * mat; } else { const Matrix pp = power(mat, n / 2); return pp * pp; } } int main() { cin.tie(0); ios::sync_with_stdio(false); long long N_, M_; cin >> N_ >> M_; N = N_; M = M_; Matrix mat; mat.table[0][0] = 2; mat.table[0][1] = 3; mat.table[1][0] = 1; mat.table[1][1] = 2; const ll mod = M * (M - 1) * (M + 1); const Matrix ans = power(mat, power(N, mod)); cout << (long long)(2 * ans.table[0][0] + M - 2) % (long long)M << endl; return 0; }