#include <bits/stdc++.h>
using namespace std;
int n, m;
long long dp[60];
int main() {
  scanf("%d%d", &n, &m);
  long long tmp = 1, ans = 1;
  dp[0] = 3;
  for (int i = 1; (1LL << i) <= n; i++) dp[i] = (dp[i - 1] * dp[i - 1]) % m;
  for (int i = 0; (1LL << i) <= n; i++)
    if ((1LL << i) & n) ans = (ans * dp[i]) % m;
  ans = (ans - 1 + m) % m;
  cout << ans << endl;
  return 0;
}
