#include <bits/stdc++.h>
using namespace std;
const long long inf = 0x3f3f3f3f;
const long long mod = 1e9 + 7;
const int N = 1000000;
template <class T1, class T2, class T3>
void printTuple(tuple<T1, T2, T3> t) {
  cout << get<0>(t) << " " << get<1>(t) << " " << get<2>(t) << '\n';
}
template <class T1, class T2>
void printPair(pair<T1, T2> p) {
  cout << p.first << " " << p.second << '\n';
}
template <class T>
void printArray(vector<T> arr) {
  for (int i = 0; i < int((arr).size()); i++) {
    cout << arr[i] << " ";
  }
  cout << '\n';
}
template <class T>
void read(vector<T> &a, int n) {
  for (int i = 0; i < n; i++) cin >> a[i];
}
template <class T>
void read(T *a, int n) {
  for (int i = 0; i < n; i++) cin >> a[i];
}
template <class T>
void readIdx(vector<pair<T, int>> &a, int n) {
  for (int i = 0; i < n; i++) {
    cin >> a[i].first;
    a[i].second = i;
  }
}
long long binpow(long long a, long long b, long long m) {
  if (!b) return 1;
  if (b == 1ll) return a % m;
  long long ret = binpow(a, b / 2, m);
  ret = (ret * ret) % m;
  if (b & 1) ret = (ret * (a % m)) % m;
  return ret;
}
int main() {
  std::ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long n, m;
  cin >> n >> m;
  long long ret = binpow(3, n, m);
  cout << (ret - 1 + m) % m << '\n';
}
