#include <bits/stdc++.h>
using namespace std;
int main() {
  long long b, p, m, r = 1;
  cin >> p >> m;
  b = 3;
  while (p) {
    if (p % 2) {
      r = ((r % m) * (b % m)) % m;
    }
    p /= 2;
    b = ((b % m) * (b % m)) % m;
  }
  r--;
  if (r < 0) r = m - 1;
  cout << r << endl;
  return 0;
}
