#include <bits/stdc++.h>
using namespace std;
int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (!isdigit(ch)) {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (isdigit(ch)) {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
long long n, mod;
long long ksm(long long x, int y) {
  long long rtn = 1;
  while (y) {
    if (y & 1) rtn = (rtn * x) % mod;
    y >>= 1;
    x = (x * x) % mod;
  }
  return rtn;
}
int main() {
  n = read(), mod = read();
  printf("%I64d\n", (ksm(3, n) - 1 + mod) % mod);
  return 0;
}
