#include <bits/stdc++.h>
using namespace std;
long long Mod, n;
long long Qmod(long long x, long long n) {
  if (n == 0) return 1;
  if (n == 1) return x;
  long long ans = Qmod(x, n / 2);
  ans = (ans * ans) % Mod;
  if (n % 2) ans = (x * ans) % Mod;
  return ans;
}
int main() {
  while (cin >> n >> Mod) {
    int tem = Qmod(3, n);
    tem += Mod;
    tem -= 1;
    tem %= Mod;
    cout << tem << endl;
  }
  return 0;
}
