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