#include <bits/stdc++.h>
using namespace std;
long long power(long long base, long long exponent, long long N) {
  if (exponent == 0) {
    return 1;
  } else if (exponent == 1) {
    return base;
  } else {
    unsigned long long output(1);
    while (exponent > 0) {
      if (exponent % 2) {
        output *= base;
        output %= N;
      }
      base *= base;
      base %= N;
      exponent /= 2;
    }
    return output;
  }
  return -1;
}
int main() {
  ios ::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long n, m;
  cin >> n >> m;
  long long res = power(3, n, m);
  if (res == 0)
    cout << m - 1;
  else
    cout << (res - 1) % m;
  return 0;
}
