#include <bits/stdc++.h>
using namespace std;
const int N = 30;
const long long MOD = 2000000011;
const long long LINF = (1LL << 62);
const long double EPS = 1e-9;
int dx4[4] = {0, 0, 1, -1};
int dy4[4] = {-1, 1, 0, 0};
int dx8[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy8[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
long long modpow(long long a, long long b, long long m) {
  if (b == 0) return 1;
  long long c = modpow(a, b / 2, m);
  c = (c * c) % m;
  return (b % 2 == 0 ? c : (a * c) % m);
}
long long n, m;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  cout << (modpow(3, n, m) - 1 + m) % m << endl;
  cout.flush();
  return 0;
}
