#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
  if (a == 0 || b == 0) return abs(a - b);
  long long res = a % b;
  while (res) {
    a = b;
    b = res;
    res = a % b;
  }
  return b;
}
long long lcm(long long a, long long b) { return a * b / gcd(a, b); }
long long max(long long a, long long b) {
  if (a > b)
    return a;
  else
    return b;
}
long long min(long long a, long long b) {
  if (a < b)
    return a;
  else
    return b;
}
long long numberofdiviser(long long a) {
  long long ans = 0;
  long long i;
  for (i = 1; i * i < a; i++) {
    if (a % i == 0) ans += 2;
  }
  if (i * i == a) ans++;
  return ans;
}
void fival(long long* a, long long b, long long n) {
  for (int i = 0; i < n; i++) {
    a[i] = b;
  }
}
long long sum, ans, l, r, x;
long long ss(vector<long long> a, vector<long long>& b, int ii) {
  for (int i = ii; i < a.size(); i++) {
    b.push_back(a[i]);
    sum += a[i];
    if (b.size() > 1 && sum >= l && sum <= r && b[b.size() - 1] - b[0] >= x)
      ans++;
    ss(a, b, i + 1);
    sum -= b[b.size() - 1];
    b.pop_back();
  }
  return ans;
}
unsigned long long fact(long long n) {
  if (n == 0) return 1;
  return n * fact(n - 1);
}
unsigned long long Combinations(unsigned long long n, unsigned long long r) {
  if (r > n) return 0;
  if (r * 2 > n) r = n - r;
  if (r == 0) return 1;
  unsigned long long res = n;
  for (int i = 2; i <= r; ++i) {
    res *= (n - i + 1);
    res /= i;
  }
  return res;
}
int solve() {
  long long n, m;
  cin >> n >> m;
  long long sum = 1;
  long long ans = 1;
  for (int i = 0; i < 10000; i++) {
    sum *= 3;
    sum %= m;
  }
  for (int i = 0; i < n / 10000; i++) {
    ans *= sum;
    ans %= m;
  }
  n %= 10000;
  for (int i = 0; i < n; i++) {
    ans *= 3;
    ans %= m;
  }
  if (ans == 0) ans = m;
  cout << (ans - 1) % m;
  return 0;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t = 1;
  while (t--) {
    solve();
  }
}
