#include <bits/stdc++.h>
using namespace std;
long long n, mod;
long long fast(long long base, long long pow) {
  long long res = 1;
  while (pow) {
    if (pow % 2) res = ((res % mod) * (base % mod)) % mod;
    pow /= 2;
    base = ((base % mod) * (base % mod)) % mod;
    if (!base) base = mod;
  }
  return res;
}
int main() {
  cin >> n >> mod;
  long long res = ((long long)(2 * ((1 - fast(3, n)) / -2.0)) % mod);
  if (res == -1)
    cout << mod - 1 << endl;
  else
    cout << res << endl;
  return 0;
}
