#include <bits/stdc++.h>
using namespace std;
int m;
void mul(int *a, int *b) {
  int res[4];
  res[0] = (((long long)a[0]) * b[0] + ((long long)b[1]) * a[2]) % m;
  res[1] = (((long long)a[1]) * b[0] + ((long long)b[1]) * a[3]) % m;
  res[2] = (((long long)a[0]) * b[2] + ((long long)b[3]) * a[2]) % m;
  res[3] = (((long long)a[1]) * b[2] + ((long long)b[3]) * a[3]) % m;
  memcpy(a, res, sizeof(res));
}
void pow(int *a, int n) {
  int ap[4] = {a[0], a[1], a[2], a[3]};
  int res[4] = {1, 0, 0, 1};
  while (n) {
    if (n & 1) mul(res, ap);
    mul(ap, ap);
    n >>= 1;
  }
  memcpy(a, res, sizeof(res));
}
int main() {
  int n, i;
  scanf("%d%d", &n, &m);
  n--;
  if (n == 0) {
    printf("%d", 2 % m);
    return 0;
  }
  int a[4] = {1, 0, 2, 3};
  int b[4];
  int res[4];
  pow(a, n);
  int resi = ((long long)a[2] + ((long long)a[3] * 2)) % m;
  printf("%d", resi);
}
