#include <bits/stdc++.h>
long long n, m, ans = 1, pw[30] = {3};
int main() {
  scanf("%lld %lld", &n, &m);
  for (int i = 1; i < 30; i++) pw[i] = (pw[i - 1] * pw[i - 1]) % m;
  for (long long i = 0; i < 30; i++)
    if (n & (1 << i)) ans = (ans * pw[i]) % m;
  printf("%lld\n", (ans + m - 1) % m);
  return 0;
}
