#include <bits/stdc++.h>
using namespace std;
void fast() {
  ios_base::sync_with_stdio(NULL);
  cin.tie(0);
  cout.tie(0);
}
void online_judge() {
  freopen("input.txt", "r", stdin);
  freopen("output.txt", "w", stdout);
}
const int flag_max = 0x3f3f3f3f;
const long long OO = 1e9;
const double EPS = (1e-7);
int dcmp(double x, double y) { return fabs(x - y) <= EPS ? 0 : x < y ? -1 : 1; }
long long gcd(long long a, long long b) { return !b ? a : gcd(b, a % b); }
long long lcm(long long a, long long b) { return (a / gcd(a, b)) * b; }
int dx[8] = {1, -1, 0, 0, 1, 1, -1, -1};
int dy[8] = {0, 0, -1, 1, 1, -1, 1, -1};
int n, m, len, limit_mask;
int distace[25][25][11];
int dp[11][1 << 11];
vector<pair<int, int>> number_of_tiles;
char grid[25][25];
bool valid(int i, int j) {
  return i >= 0 && i <= n - 1 && j >= 0 && j <= m - 1 && grid[i][j] != 'x';
}
void BFS_for_every_i(int indx) {
  queue<pair<int, int>> q;
  bool vis[n][m];
  int X = number_of_tiles[indx].first, Y = number_of_tiles[indx].second;
  q.push({X, Y});
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      vis[i][j] = 0;
      distace[i][j][indx] = OO;
    }
  }
  vis[X][Y] = 1;
  distace[X][Y][indx] = 0;
  while (!q.empty()) {
    pair<int, int> Q = q.front();
    q.pop();
    int X = Q.first, Y = Q.second;
    for (int k = 0; k < 4; k++) {
      if (valid(X + dx[k], Y + dy[k]) && !vis[X + dx[k]][Y + dy[k]]) {
        vis[X + dx[k]][Y + dy[k]] = 1;
        distace[X + dx[k]][Y + dy[k]][indx] = distace[X][Y][indx] + 1;
        q.push({X + dx[k], Y + dy[k]});
      }
    }
  }
}
int solve(int indx, int mask) {
  if (mask == limit_mask) {
    return 0;
  }
  if (dp[indx][mask] != -1) {
    return dp[indx][mask];
  }
  int ans = OO;
  for (int i = 0; i < len; i++) {
    if ((mask & 1 << i) == 0) {
      int new_mask = mask | 1 << i;
      ans = min(ans, solve(i, new_mask) +
                         distace[number_of_tiles[i].first]
                                [number_of_tiles[i].second][indx]);
    }
  }
  return dp[indx][mask] = ans;
}
long long pow__(long long n, long long mod) {
  long long ans;
  if (n == 0) {
    return 1;
  }
  ans = pow__(n / 2, mod);
  if (n % 2 == 0)
    return (ans * ans) % mod;
  else {
    if (n > 0)
      return (3 * (ans * ans) % mod) % mod;
    else
      return ((ans * ans) % mod / 3) % mod;
  }
}
int main() {
  fast();
  long long n, m;
  cin >> n >> m;
  long long ans = 2 * (1 - pow__(n, m));
  ans /= -2;
  ans %= m;
  ans < 0 ? ans += m : ans;
  cout << ans;
  return 0;
}
