#include <bits/stdc++.h>
using namespace std;
long long FastPowering(long long k, long long p, long long m) {
  if (p == 0) return 1 % m;
  if (p % 2 == 0) {
    long long ans = FastPowering(k, p / 2, m);
    ans = (ans * ans) % m;
    return ans;
  } else {
    long long ans = FastPowering(k, p / 2, m);
    ans = (ans * ans) % m;
    ans = (ans * k) % m;
    return ans;
  }
}
int main() {
  long long n, m;
  long long power;
  long long answer;
  scanf("%I64d %I64d", &n, &m);
  power = FastPowering(3, n, m);
  answer = power - 1;
  if (answer < 0) answer = answer + m;
  printf("%I64d\n", answer);
  return 0;
}
