#include <bits/stdc++.h>
using namespace std;
long long f(long long n, long long m) {
  if (n == 0ll) return 1ll;
  long long tmp = f(n / 2, m);
  if (n % 2ll)
    return (((tmp) * (tmp)) * 3ll) % m;
  else
    return (((tmp) * (tmp))) % m;
}
int main() {
  ios_base::sync_with_stdio(false);
  long long n, m;
  cin >> n >> m;
  cout << (f(n, m) + m - 1ll) % m << endl;
}
