#include <bits/stdc++.h>
using namespace std;
int i, j, k, m, n, l;
long long pow(long long a, long long b, long long mod) {
  long long ret = 1;
  while (b) {
    if (b & 1) ret = (ret * a) % mod;
    a = (a * a) % mod;
    b >>= 1;
  }
  return ret;
}
int main() {
  while (cin >> n >> m) {
    cout << (pow(3, n, m) - 1 + m) % m << endl;
  }
  return 0;
}
