#include <bits/stdc++.h>
using namespace std;
long long qqq(long long x, long long p, long long m) {
  long long ans = 1;
  long long t = x;
  while (p > 0) {
    if (p & 1 != 0) ans = ans * t % m;
    t = t * t % m;
    p = p >> 1;
  }
  return ans;
}
int main() {
  long long N, K;
  cin >> N >> K;
  if (K == 1) {
    cout << 0 << endl;
    return 0;
  }
  long long R = qqq(3, N, K);
  if (R == 0)
    cout << K - 1 << endl;
  else
    cout << R - 1 << endl;
}
