#include <bits/stdc++.h>
using namespace std;
int N, M;
int main() {
  scanf("%d %d", &N, &M);
  long long ans = 1;
  long long p = 3;
  while (N > 0) {
    if (N & 1) ans = (ans * p) % M;
    p = (p * p) % M;
    N /= 2;
  }
  printf("%d", (int)((ans + M - 1) % M));
  return 0;
}
