#include <bits/stdc++.h>
using namespace std;
int j, i, p, k, m, a[111][111], b[111111];
long long n, t, t2;
long long step(int n) {
  long long r = 3, ans = 1;
  for (; n; n /= 2) {
    if (n & 1) ans = (ans * r) % m;
    r = (r * r) % m;
  }
  return ans;
}
int main() {
  cin >> n >> m;
  t = step(n);
  cout << (t + m - 1) % m;
}
