#include <bits/stdc++.h>
using namespace std;
int n, k, m;
const int maxn = 100;
void mult(int **a, int **b, int **c, int n, int l) {
  long long tmp[maxn][maxn];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      tmp[i][j] = 0;
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < l; j++) {
      for (int k = 0; k < n; k++) {
        tmp[i][j] += (long long)a[i][k] * b[k][j];
        tmp[i][j] %= m;
      }
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < l; j++) {
      c[i][j] = tmp[i][j];
    }
  }
}
void pwm(int **x, int **res, int k, int n) {
  if (k == 1) {
    return;
  } else {
    if (k % 2 == 0) {
      pwm(x, res, k / 2, n);
      mult(res, res, res, n, n);
    } else {
      pwm(x, res, k - 1, n);
      mult(x, res, res, n, n);
    }
  }
}
int main() {
  cin >> n >> m;
  if (n == 1) {
    cout << 2 % m;
    return 0;
  }
  int **a = new int *[maxn], **b = new int *[maxn], **c = new int *[maxn];
  for (int i = 0; i < maxn; i++) {
    a[i] = new int[maxn];
    b[i] = new int[maxn];
    c[i] = new int[maxn];
  }
  a[0][0] = 3;
  a[0][1] = a[1][1] = a[1][2] = a[2][0] = a[2][1] = 0;
  a[0][2] = a[1][0] = a[2][2] = 1;
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      c[i][j] = a[i][j];
    }
  }
  b[0][0] = 1;
  b[1][0] = 0;
  b[2][0] = 1;
  pwm(c, a, n - 1, 3);
  mult(a, b, b, 3, 1);
  cout << (2 * b[0][0]) % m;
}
