#include <bits/stdc++.h>
using namespace std;
long long n, m;
long long Fast_Exponenciation(long long n, long long p) {
  long long nlaput = n, ans = 1;
  while (p) {
    if (p % 2 == 1)
      if (ans * nlaput % m == 0)
        ans = m;
      else
        ans = ans * nlaput % m;
    if (nlaput * nlaput % m == 0)
      nlaput = m;
    else
      nlaput = nlaput * nlaput % m;
    p /= 2;
  }
  return ans;
}
int main() {
  cin >> n >> m;
  cout << Fast_Exponenciation(3, n) - 1;
  return 0;
}
