#include <bits/stdc++.h>
int pow(int n, int m) {
  long long a = 3;
  int ret = 1;
  while (n) {
    if (n & 1) ret = (ret * a) % m;
    a = (a * a) % m;
    n >>= 1;
  }
  ret += m - 1;
  return ret %= m;
}
int main() {
  int n, m;
  while (~scanf("%d%d", &n, &m)) printf("%d\n", pow(n, m));
  return 0;
}
