#include <bits/stdc++.h>
using namespace std;
long long i, n, m, second;
long long mul(long long k) {
  if (k == 0) return 1;
  if (k == 1) return 3;
  if (k % 2 == 0) {
    long long x = mul(k / 2);
    return (x * x) % m;
  }
  return ((3 * mul(k - 1)) % m);
}
int main() {
  cin >> n >> m;
  second = mul(n) % m;
  if (second == 0) second += m;
  second--;
  cout << second;
  return 0;
}
