#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline T Abs(const T& value) {
  return value < 0 ? -value : value;
}
template <typename T>
inline T Sqr(const T& value) {
  return value * value;
}
long long m;
void Mul(long long a[2][2], long long b[2][2], long long c[2][2]) {
  memset(c[0], 0, sizeof(c[0]));
  memset(c[1], 0, sizeof(c[1]));
  for (int i = 0; i < 2; ++i)
    for (int j = 0; j < 2; ++j)
      for (int k = 0; k < 2; ++k) c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % m;
}
void Step(long long a[2][2], long long step, long long res[2][2]) {
  memset(res[0], 0, sizeof(res[0]));
  memset(res[1], 0, sizeof(res[1]));
  res[0][0] = 1;
  res[1][1] = 1;
  long long tmp[2][2];
  while (step > 0) {
    if (step % 2) {
      Mul(a, res, tmp);
      memcpy(res[0], tmp[0], sizeof(res[0]));
      memcpy(res[1], tmp[1], sizeof(res[1]));
    }
    step /= 2;
    Mul(a, a, tmp);
    memcpy(a[0], tmp[0], sizeof(res[0]));
    memcpy(a[1], tmp[1], sizeof(res[1]));
  }
}
int main() {
  long long n;
  cin >> n >> m;
  long long a[2][2], b[2][2];
  a[0][0] = 3;
  a[0][1] = 2;
  a[1][0] = 0;
  a[1][1] = 1;
  Step(a, n - 1, b);
  cout << (b[0][0] * 2 + b[0][1] * 1) % m << endl;
  return 0;
}
