#include <bits/stdc++.h>
using namespace std;
const int inf = 1 << 30;
const long long infl = 1LL << 60;
char buf[1000000];
string nextLine() {
  scanf("%[^\n]", buf);
  scanf("%*c");
  return string(buf);
}
string next() {
  scanf("%s", buf);
  return string(buf);
}
int nextInt() {
  int tmp;
  scanf("%d", &tmp);
  return tmp;
}
int pow(int N, int M) {
  if (N == 0) return 1;
  long long k = pow(N / 2, M);
  k = (k * k) % M;
  if (N % 2 == 1) k = (k * 3) % M;
  return k;
}
int main() {
  int N = nextInt(), M = nextInt();
  int p = pow(N, M);
  (p += M - 1) %= M;
  cout << p << endl;
}
