#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  cin >> n >> m;
  int res = 1;
  for (int i = 30; i >= 0; i--) {
    res = (res * (long long)res) % m;
    if (n & (1 << i)) res = (res * 3LL) % m;
  }
  res = (res + m - 1) % m;
  cout << res << endl;
}
