#include <bits/stdc++.h>
using namespace std;
long long m;
int matrix[2][2] = {{3, 1}, {0, 1}};
class Matrix {
 public:
  long long c[2][2];
  Matrix() {
    for (int i = 0; i < 2; i++)
      for (int j = 0; j < 2; j++) c[i][j] = 0;
  }
  void deal() {
    for (int i = 0; i < 2; i++)
      for (int j = 0; j < 2; j++) c[i][j] = matrix[i][j];
  }
};
Matrix mul(const Matrix& t1, const Matrix& t2) {
  int i, j, k;
  Matrix t3;
  for (i = 0; i < 2; i++) {
    for (j = 0; j < 2; j++) {
      for (k = 0; k < 2; k++) {
        t3.c[i][j] = (t3.c[i][j] + t1.c[i][k] * t2.c[k][j]) % m;
      }
    }
  }
  return t3;
}
Matrix power(long long n) {
  Matrix a, b;
  b.deal();
  if (n == 1)
    return b;
  else if (n % 2 == 1) {
    a = (power(n / 2));
    return mul(mul(a, a), b);
  } else {
    a = (power(n / 2));
    return mul(a, a);
  }
}
int main() {
  long long n;
  while (cin >> n >> m) {
    if (n == 1) {
      cout << 2 % m << endl;
      continue;
    } else {
      Matrix s = power(n - 1);
      cout << (s.c[0][0] * 2 + s.c[0][1] * 2) % m << endl;
    }
  }
  return 0;
}
