#include <bits/stdc++.h>
using namespace std;
void solve(long long n, long long m) {
  long long result = 1, x = 3;
  x %= m;
  if (x == 0) cout << ' ';
  while (n > 0) {
    if (n & 1) result = (result * x) % m;
    n /= 2;
    x = (x * x) % m;
  }
  result = result % m - 1 % m;
  if (result < 0) result = (result + m) % m;
  cout << result;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  long long n, m;
  cin >> n >> m;
  solve(n, m);
}
