#include <bits/stdc++.h>
using namespace std;
long long mypow3(long long p, long long mod) {
  long long rez = 1, x = 3;
  while (p > 0) {
    if (p % 2 == 1) rez = (rez * x) % mod;
    x = (x * x) % mod;
    p /= 2;
  }
  return rez;
}
int main() {
  long long n, m, ans;
  ios_base::sync_with_stdio(false);
  cin >> n >> m;
  ans = mypow3(n, m) - 1;
  if (ans == -1) ans = m - 1;
  cout << ans << '\n';
  return 0;
}
