#include <bits/stdc++.h>
using namespace std;
int N, M, cnt;
long long int F;
map<long long int, long long int> P;
long long int pow(int val, int p) {
  long long int v;
  if (P.find(p) != P.end()) return P.find(p)->second;
  if (p == 1) return 3 % M;
  if (p % 2) {
    v = (val * pow(val, p / 2) * pow(val, p / 2)) % M;
  } else {
    v = (pow(val, p / 2) * pow(val, p / 2)) % M;
  }
  P.insert(make_pair(p, v));
  return v;
}
int main() {
  cin >> N >> M;
  F = pow(3, N) - 1;
  if (F == -1) F = M - 1;
  cout << F << endl;
  return 0;
}
