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