#include
#include<string.h>
#include
#include
#include
#include
using namespace std;
const int N=1e4+10;
const int INF=0x3f3f3f3f;
const int MOD=1e9+7;
typedef long long LL;
LL Solve(LL a, LL b, LL m) ///快速幂
{
LL t, sum;
t = a % m;
sum = 1;
while (b)
{
if(b&1) sum = (sum*t)%m;
t = (t*t)%m;
b /= 2;
}
return sum;
}
int main ()
{
LL n, m, ans;
while (scanf("%lld %lld", &n, &m) != EOF)
{
ans = Solve(2, n+1, 3*m);
if (n % 2 == 0) ans = (ans-2)/3;
else ans = (ans-1)/3;
printf("%lld\n", ans);
}
return 0;
}