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