#include <bits/stdc++.h>
using namespace std;
int MOD = 1e9 + 7;
void inc(int &x, int y) {
  x += y;
  if (x >= MOD) x -= MOD;
}
struct Mat {
  static const int N = 2;
  int a[N][N];
  void init(int x) {
    for (int i = (0); i < (2); ++i)
      for (int j = (0); j < (2); ++j) a[i][j] = (i == j ? x : 0);
  }
  Mat operator*(const Mat &p) {
    Mat ret;
    ret.init(0);
    for (int i = (0); i < (N); ++i)
      for (int j = (0); j < (N); ++j)
        for (int k = (0); k < (N); ++k)
          inc(ret.a[i][j], 1ll * a[i][k] * p.a[k][j] % MOD);
    return ret;
  }
  Mat operator^(long long b) {
    Mat ret, a = *this;
    ret.init(1);
    while (b > 0) {
      if (b & 1) ret = ret * a;
      a = a * a, b >>= 1;
    }
    return ret;
  }
} A;
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  MOD = m;
  A.a[0][0] = 3, A.a[0][1] = 2;
  A.a[1][0] = 0, A.a[1][1] = 1;
  A = A ^ (n - 1);
  int ans = (2ll * A.a[0][0] + A.a[0][1]) % MOD;
  printf("%d", ans);
  return 0;
}
