#include <bits/stdc++.h>
using namespace std;
int T;
long long N, MOD;
struct matrix {
  long long mat[3][3];
} sol, X, B;
matrix operator*(const matrix& A, const matrix& B) {
  matrix ret;
  memset(ret.mat, 0, sizeof ret.mat);
  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 2; ++j) {
      for (int k = 0; k < 2; ++k) {
        ret.mat[i][j] += A.mat[i][k] * B.mat[k][j];
      }
      ret.mat[i][j] %= MOD;
    }
  }
  return ret;
}
void init() {
  memset(sol.mat, 0, sizeof sol.mat);
  memset(X.mat, 0, sizeof X.mat);
  memset(B.mat, 0, sizeof B.mat);
  sol.mat[0][0] = sol.mat[1][1] = 1;
  B.mat[0][0] = 0;
  B.mat[0][1] = 2;
  X.mat[0][0] = 3;
  X.mat[1][0] = X.mat[1][1] = 1;
}
void solve() {
  scanf("%I64d %I64d", &N, &MOD);
  init();
  while (N > 0) {
    if (N & 1) sol = sol * X;
    N >>= 1;
    X = X * X;
  }
  sol = B * sol;
  printf("%I64d\n", sol.mat[0][0]);
}
int main(void) {
  solve();
  return 42 - 42;
}
