#include <bits/stdc++.h>
int n, m;
int b[1000];
int len;
void bin(int x) {
  len = 0;
  int temp = x;
  while (x > 0) {
    len++;
    x = x / 2;
  }
  b[len] = 10;
  x = temp;
  while (x > 0) {
    b[--len] = x % 2;
    x = x / 2;
  }
}
int pow_mod() {
  long long sum = 1;
  for (int i = 0; b[i] != 10; i++) {
    sum = (sum * sum) % m;
    if (b[i] == 1) sum = (sum * 3) % m;
  }
  return (int)(sum % m);
}
int main() {
  scanf("%d %d", &n, &m);
  int sum = m - 1;
  bin(n);
  sum += pow_mod();
  printf("%d", sum % m);
}
