#include <bits/stdc++.h>
long long int n, m;
long long int pow(long long int k) {
  long long int a = 1, t = 3;
  for (; k; k /= 2) {
    if (k & 1) a = (a * t) % m;
    t = t * t % m;
  }
  return a;
}
void suru() { scanf("%I64d %I64d", &n, &m); }
void truli() {}
void sutru() { printf("%I64d\n", (pow(n) - 1 + m) % m); }
int main() {
  suru();
  truli();
  sutru();
  return 0;
}
