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