#include <bits/stdc++.h>
using namespace std;
ifstream in("flying_saucer_segments.in");
ofstream out("flying_saucer_segments.out");
int main() {
  int n, m, rez = 1, ct = 3;
  cin.sync_with_stdio(false);
  cin >> n >> m;
  for (int i = 0; (1 << i) <= n; i++) {
    if (((1 << i) & n) != 0) rez = (1LL * rez * ct) % m;
    ct = (1LL * ct * ct) % m;
  }
  cout << (rez - 1 + m) % m;
  return 0;
}
