#include <bits/stdc++.h>
using namespace std;
const long double PI = 3.1415926535897932384626433832795;
const long double EPS = 1e-11;
signed long long st = 3, n, m, ans = 1;
vector<bool> v;
void trans(int n) {
  while (n > 0) {
    v.push_back(n % 2);
    n /= 2;
  }
}
int main() {
  cout << setiosflags(ios::fixed) << setprecision(10);
  cin >> n >> m;
  trans(n);
  for (int i = 0; i < (v.size()); i++) {
    if (v[i]) ans = (ans * st) % m;
    st = (st * st) % m;
  }
  cout << (ans + m - 1) % m;
  return 0;
}
