#include <bits/stdc++.h>
int m;
long long power3mod(int n) {
  if (n == 0) return 1;
  if (n == 1) return 3;
  long long temp = power3mod(n / 2) % m;
  if (n % 2 == 0)
    return (temp * temp) % m;
  else
    return (temp * temp * 3) % m;
}
int main() {
  int n;
  long long ans;
  scanf("%d %d", &n, &m);
  ans = power3mod(n);
  ans = (ans - 1) % m;
  if (ans < 0) ans += m;
  printf("%I64d", ans);
  return 0;
}
