#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const int inf = (int)1e9;
const long long int infll = (long long int)1e18;
const double inf1 = 1e-9;
const int ss = (int)1e6 + 3;
const int base = inf;
bool pred(const pair<int, int>& i, const pair<int, int>& j) {
  if (i.first == j.first)
    return i.second < j.second;
  else
    return i.first < j.first;
}
bool pred2(const pair<pair<int, int>, int> i, pair<pair<int, int>, int> j) {
  if ((i.first.second - i.first.first) == (j.first.second - j.first.first))
    return i.first.second < j.first.second;
  else
    return (i.first.second - i.first.first) < (j.first.second - j.first.first);
}
bool pred3(const int& i, const int& j) { return i < j; }
long long int mod;
long long int binpow(long long int a, long long int n) {
  int res = 1;
  while (n) {
    if (n & 1) res = (res * a) % mod;
    a = (a * a) % mod;
    n >>= 1;
  }
  return res;
}
int main() {
  long long int n, m;
  cin >> n >> m;
  mod = m;
  long long int res = binpow(3, n);
  if (res - 1 < 0) res += m;
  cout << res - 1;
  return 0;
}
