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