#include <bits/stdc++.h>
using namespace std;
long long int M;
long long int mypow(long long int a, long long int b) {
  long long int ans = 1, pre = a;
  while (b != 0) {
    if (b % 2 == 1) ans = (ans * pre) % M;
    pre = (pre * pre) % M;
    b = b / 2;
  }
  return ans;
}
int main() {
  int i, j;
  long long int n;
  cin >> n >> M;
  cout << (mypow(3, n) - 1 + M) % M << endl;
  return 0;
}
