#include <bits/stdc++.h>
using namespace std;
long long n, m, x = 3, q = 1;
int main() {
  scanf(
      "%lld"
      "%lld",
      &n, &m);
  while (n > 1) {
    if (n % 2 == 1) q = (q * x) % m;
    x = (x * x) % m;
    n /= 2;
  }
  x = (x * q) % m - 1;
  printf("%lld", (x + m) % m);
  return 0;
}
