#include <bits/stdc++.h>
using namespace std;
int n, m;
long long bin_pow(long long x, int n) {
  if (n == 0)
    return 1;
  else if (n % 2 == 0) {
    return bin_pow((x * x) % m, n / 2);
  } else {
    return (x * bin_pow((x * x) % m, n / 2)) % m;
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin >> n >> m;
  int tmp = bin_pow(3, n);
  if (tmp == 0)
    cout << m - 1 << endl;
  else
    cout << bin_pow(3, n) - 1;
  return 0;
}
