#include <bits/stdc++.h>
using namespace std;
int64_t CONST;
int64_t POWER(int64_t n, int64_t m) {
  if (m == 1)
    return n % CONST;
  else if (m != 2 && m % 2 == 0)
    return POWER(POWER(n, m / 2), 2) % CONST;
  else if (m != 2 && m % 2 == 1)
    return (POWER(n, m - 1) % CONST) * (POWER(n, 1) % CONST);
  else if (m == 2)
    return (n % CONST) * (n % CONST);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL), cout.tie(NULL);
  int n, m;
  cin >> n >> m;
  CONST = m;
  int64_t ans = POWER(3, n) % m;
  if (ans == 0) ans = m;
  cout << ans - 1;
}
