#include <bits/stdc++.h>
using namespace std;
int n, m;
long long binpow(long long a, int p) {
  if (!p) return 1;
  if (p % 2) return (a * binpow(a, p - 1)) % m;
  long long b = binpow(a, p / 2) % m;
  return (b * b) % m;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin >> n >> m;
  if (m == 1) {
    cout << 0;
    return 0;
  }
  long long q = binpow(3, n);
  if (q <= 0) q += m;
  long long ans = (q - 1) % m;
  cout << ans;
  return 0;
}
