#include <bits/stdc++.h>
using namespace std;
long long int exp(long long int x, long long int n, long long int m) {
  if (!n) return 1;
  if (n == 1) return x % m;
  if (n == 2) return (x * x) % m;
  if (n % 2 == 0)
    return (exp(exp(x, n / 2, m) % m, 2, m)) % m;
  else
    return (x * exp((exp(x, (n - 1) / 2, m)) % m, 2, m)) % m;
}
int main() {
  long long int n, m;
  cin >> n >> m;
  long long int a = exp(3, n, m) - 1;
  if (a < 0) {
    a += m;
  }
  long long int k = (a / 2) % m;
  if (a % 2) {
    cout << ((2 * k) + 1) % m << endl;
  } else
    cout << (2 * k) % m << endl;
}
