#include <bits/stdc++.h>
using namespace std;
long long a_exp_b_mod_c(long long a, long long b, long long c) {
  long long ans = 1;
  while (b > 0) {
    if ((b & 1) == 1) ans = ((ans % c) * (a % c)) % c;
    b /= 2;
    a = ((a % c) * (a % c)) % c;
  }
  return ans;
}
int main() {
  long long n, m;
  while (cin >> n >> m) {
    long long ans = a_exp_b_mod_c(3, n, m);
    cout << (ans - (1 % m) + m) % m << endl;
  }
  return 0;
}
