#include <bits/stdc++.h>
using namespace std;
const int OO = 0x3f3f3f3f;
const int _OO = -1 * OO;
const double EPS = (1e-9);
const double pi = 3.14159265;
using namespace std;
int dcmp(double x, double y) { return fabs(x - y) <= EPS ? 0 : x < y ? -1 : 1; }
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, -1, 1};
int dx8[8] = {1, 1, 1, 0, 0, -1, -1, -1};
int dy8[8] = {1, -1, 0, 1, -1, 1, -1, 0};
const int N = 100;
long long n, m;
long long A[N][N], I[N][N];
long long pow_N(long long a, long long n) {
  long long res = 1;
  while (n) {
    if (n % 2) {
      res = (res * a) % m, n--;
    } else {
      a = (a * a) % m, n /= 2;
    }
  }
  return res % m;
}
void mult(long long A[][N], long long B[][N], long long dim) {
  long long res[dim + 1][dim + 1];
  for (int i = 0; i < (int)(dim); ++i) {
    for (int j = 0; j < (int)(dim); ++j) {
      res[i][j] = 0;
      for (int k = 0; k < (int)(dim); ++k) {
        res[i][j] += A[i][k] * B[k][i];
      }
    }
  }
  for (int i = 0; i < (int)(dim); ++i) {
    for (int j = 0; j < (int)(dim); ++j) {
      A[i][j] = res[i][j];
    }
  }
}
void mat_pow(long long A[][N], int dim, int n) {
  for (int i = 0; i < (int)(dim); ++i)
    for (int j = 0; j < (int)(dim); ++j) {
      if (i == j)
        I[i][j] = 1;
      else
        I[i][j] = 0;
    }
  while (n) {
    if (n % 2)
      mult(I, A, dim), n--;
    else
      mult(A, A, dim), n /= 2;
  }
  for (int i = 0; i < (int)(dim); ++i)
    for (int j = 0; j < (int)(dim); ++j) A[i][j] = I[i][j];
}
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n >> m;
  long long ans = (pow_N(3, n) - 1);
  if (ans < 0)
    cout << m - 1;
  else
    cout << ans;
  return 0;
}
