#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000510;
const int maxm = 210;
const int INF = 1e9;
const int mod1 = 1e9 + 7;
const int mod2 = 123456701;
int n, m;
long long calc(long long x, long long y) {
  long long ret = 1;
  long long gg = 3;
  while (x) {
    if (x & 1) {
      ret *= gg;
    }
    gg *= gg;
    gg %= y;
    ret %= y;
    x >>= 1;
  }
  return ret;
}
int main() {
  int i, j;
  while (scanf("%d%d", &n, &m) != EOF) {
    long long ans = calc(n, m);
    ans = (ans - 1 + m) % m;
    cout << ans << endl;
  }
  return 0;
}
