#include <bits/stdc++.h>
using namespace std;
int n, m;
long long int matriz[2][2];
void mul(long long int a[2][2], long long int b[2][2], long long int c[2][2],
         long long int m) {
  for (int i = 0; i < (2); i++) {
    for (int j = 0; j < (2); j++) {
      c[i][j] = 0;
      for (int k = 0; k < (2); k++) {
        c[i][j] = (c[i][j] + (a[i][k] * b[k][j]) % m) % m;
      }
    }
  }
}
void copia(long long int a[2][2], long long int b[2][2], long long int m) {
  for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 2; j++) {
      a[i][j] = b[i][j] % m;
    }
  }
}
void expo(long long int y[2][2], long long int b, long long int m,
          long long int x[2][2]) {
  x[0][0] = 1;
  x[0][1] = 0;
  x[1][0] = 0;
  x[1][1] = 1;
  long long int aux[2][2];
  while (b > 0) {
    if (b % 2 == 1) {
      mul(x, y, aux, m);
      copia(x, aux, m);
    }
    mul(y, y, aux, m);
    copia(y, aux, m);
    b = b / 2;
  }
}
int main() {
  scanf("%d %d", &n, &m);
  matriz[0][0] = 3;
  matriz[0][1] = 0;
  matriz[1][0] = 2;
  matriz[1][1] = 1;
  long long int x[2][2];
  expo(matriz, n, m, x);
  cout << x[1][0] << '\n';
  return 0;
}
