#include <bits/stdc++.h>
using namespace std;
template <class T>
inline void chmax(T &x, T &y) {
  if (x < y) swap(x, y);
}
template <class T>
inline void chmin(T &x, T &y) {
  if (x > y) swap(x, y);
}
const long long INF = 0x3f3f3f3f3f3f;
const long long MOD = 1e9 + 7;
const long double EPS = 10e-10;
long long binPow(long long b, long long e, long long m) {
  long long res = 1;
  while (e > 0) {
    if (e & 1) res = res * b % m;
    b = (b * b) % m;
    e >>= 1;
  }
  return res;
}
void Solution() {
  long long n, m, ans;
  scanf("%lld %lld", &n, &m);
  ans = binPow(3, n, m) - 1;
  if (ans < 0) ans += m;
  printf("%lld", ans);
}
int32_t main() {
  long long tc = 1;
  for (long long tn = 1; tn < tc + 1; tn += 1) {
    Solution();
  }
  return 0;
}
