#include <bits/stdc++.h>
using namespace std;
const int INT_INF = 0x3fffffff;
const long long LL_INF = 0x3fffffffffffffff;
const double EPS = 1e-9;
const double PI = 3.14159265358979323846;
const int N = 10010;
const int E = 10010;
long long MOD;
long long power(long long n, long long p) {
  if (p == 0) return 1;
  long long odd = 1;
  while (p > 1) {
    if (p & 1) odd = (odd * n) % MOD;
    n = (n * n) % MOD;
    p /= 2;
  }
  return (n * odd) % MOD;
}
int main() {
  long long n;
  while (~scanf("%I64d%I64d", &n, &MOD)) {
    long long ans = power(3, n) - 1;
    if (ans < 0) ans += MOD;
    printf("%I64d\n", ans);
  }
  return 0;
}
