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