#include <bits/stdc++.h>
using namespace std;
const int INF = 1000000000;
const int prime = 9241;
const long double pi = acos(-1.);
long long pow(long long a, long long b, long long m) {
  long long p = a;
  long long ans = 1ll;
  while (b) {
    if (b & 1ll) ans = (ans * p) % m;
    p = (p * p) % m;
    b >>= 1;
  }
  return ans;
}
int main() {
  long long n, m;
  cin >> n >> m;
  cout << (m + pow(3ll, n, m) - 1ll) % m << endl;
}
