#include <bits/stdc++.h>
using namespace std;
int n, m;
int f(int k, int m) {
  if (k == 0) return 1;
  int tmp = f(k >> 1, m);
  tmp = 1LL * tmp * tmp % m;
  return 1LL * ((k & 1) ? 3 : 1) * tmp % m;
}
int main() {
  cin >> n >> m;
  cout << (f(n, m) - 1 + m) % m << endl;
  return 0;
}
