#include <bits/stdc++.h>
long long calculate(int n, int m) {
  if (n == 1) {
    return 3 % m;
  } else if (n == 2) {
    return 9 % m;
  } else {
    long long tmp = calculate(n / 2, m);
    long long tmp_remainder = tmp % m;
    if (n % 2 == 0) {
      return tmp_remainder * tmp_remainder % m;
    } else {
      return tmp_remainder * tmp_remainder * 3 % m;
    }
  }
}
int main() {
  long n, m;
  scanf("%ld%ld", &n, &m);
  long long result = calculate(n, m);
  result %= m;
  if (result == 0) {
    printf("%ld", m - 1);
  } else {
    printf("%ld", result - 1);
  }
}
