#include <bits/stdc++.h>
using namespace std;
vector<bool> sieve(long long n) {
  vector<bool> prime(n + 1, true);
  prime[0] = prime[1] = false;
  for (long long i = 2; i <= n; ++i) {
    if (prime[i] && (i * i) <= n)
      for (long long j = i * i; j <= n; j += i) prime[j] = false;
  }
  return prime;
}
long long power(long long a, long long b, long long m) {
  a %= m;
  long long res = 1;
  while (b > 0) {
    if (b & 1) res = res * a % m;
    a = a * a % m;
    b >>= 1;
  }
  return res;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long n, m;
  cin >> n >> m;
  long long val = power(3, n, m);
  if (val == 0) val += m;
  cout << val - 1;
  return 0;
}
