#include <bits/stdc++.h>
using namespace std;
long long pow_m(long long n, long long mod) {
  long long ret = 1;
  long long tmp = 3;
  while (n) {
    if (n & 1) ret = ret * tmp % mod;
    tmp = tmp * tmp % mod;
    n >>= 1;
  }
  return ret;
}
int main(int argc, char *argv[]) {
  long long n, m;
  cin >> n >> m;
  cout << (pow_m(n, m) + m - 1) % m << endl;
  return 0;
}
