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