#include <bits/stdc++.h>
using namespace std;
long long a[100];
int Log(int n) {
  if (n <= 1) return 0;
  int ans = 0;
  for (int i = 1; i < n; i *= 2, ans++)
    ;
  return ans - 1;
}
int main() {
  int n, m;
  cin >> n >> m;
  int ia = 0;
  a[0] = 3 % m;
  int L = Log(n);
  while (ia <= L) {
    ia++;
    a[ia] = a[ia - 1] * a[ia - 1] % m;
  }
  string s = "";
  while (n != 0) {
    if (n % 2 == 0)
      s += '0';
    else
      s += '1';
    n /= 2;
  }
  long long ans = 1;
  for (int i = s.length() - 1; i >= 0; i--)
    if (s[i] == '1') ans = ans * a[i] % m;
  if (ans == 0)
    cout << m - 1 << endl;
  else
    cout << ans - 1 << endl;
  return 0;
}
