#include <bits/stdc++.h>
using namespace std;
long long n, m;
long long power(long long b) {
  long long a = 3, res = 1;
  while (b > 0) {
    if (b % 2) res = (res * a) % m;
    a = (a * a) % m;
    b /= 2;
  }
  return res;
}
int main() {
  cin >> n >> m;
  cout << (power(n) - 1 + m) % m;
  return 0;
}
