#include <bits/stdc++.h>
using namespace std;
int d;
uint64_t exp(uint64_t a, uint64_t n) {
  if (n == 0) return 1;
  if (n == 1) return a % d;
  if (n % 2 == 0) {
    uint64_t p = exp(a, n / 2);
    return (p * p) % d;
  } else {
    uint64_t p = exp(a, (n - 1));
    return (a * p) % d;
  }
}
void solve() {
  uint64_t n;
  cin >> n >> d;
  uint64_t ans = 0;
  ans = exp(3, n) - 1;
  if (ans == -1) ans = d - 1;
  cout << ans << "\n";
}
int main() {
  solve();
  return 0;
}
