#include <bits/stdc++.h>
using namespace std;
long long modulo;
long long power(long long exp) {
  long long res = 1, factor = 3;
  while (exp > 0) {
    if (exp & 1) res = (res * factor) % modulo;
    factor = (factor * factor) % modulo;
    exp >>= 1;
  }
  return res;
}
int main() {
  long long n;
  cin >> n >> modulo;
  long long res = power(n);
  if (res == 0)
    cout << modulo - 1;
  else
    cout << res - 1;
  return 0;
}
