#include <bits/stdc++.h>
using namespace std;
long long n, m, x = 1, s;
int main() {
  ios_base::sync_with_stdio(false);
  s = 59049;
  s *= s;
  cin >> n >> m;
  x = 1;
  while (n >= 20) {
    n -= 20;
    x *= s;
    x %= m;
  }
  for (int i = 1; i <= n; i++) {
    x *= 3;
    x %= m;
  }
  if (x == 0)
    cout << m - 1 << endl;
  else
    cout << x - 1 << endl;
  return 0;
}
