// Problem: 阅读理解
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/4827/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
#define endl '\n'
#define Carol MyWife^=^
#define pb push_back
#define pp pop_back
#define debug1(x) cout << #x << " = " << (x) << '\n'
#define debug2(x) cout << #x << " = " << (x) << ' '
//#define x first
//#define y second
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1e6+5, M = 1e6+5;
const int INF = 0x3f3f3f3f;
int n, MOD;
int nmod(int x) {
if(x < 0) x += MOD;
if(x >= MOD) x -= MOD;
return x;
}
template<class T>
T qpow(T a, LL b, LL p) {
T res = 1;
while(b) {
if(b & 1) res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
struct Mint {
int x;
Mint(int x = 0) : x(nmod(x)) {}
Mint(LL x) : x(nmod(x % MOD)) {}
int val() const {
return x;
}
Mint operator-() const {
return Mint(nmod(MOD - x));
}
Mint inv() const {
return qpow(*this, MOD - 2, MOD);
}
Mint &operator*=(const Mint &rhs) {
x = LL(x) * rhs.x % MOD;
return *this;
}
Mint &operator+=(const Mint &rhs) {
x = nmod(x + rhs.x);
return *this;
}
Mint &operator-=(const Mint &rhs) {
x = nmod(x - rhs.x);
return *this;
}
Mint &operator/=(const Mint &rhs) {
return *this *= rhs.inv();
}
friend Mint operator*(const Mint &lhs, const Mint &rhs) {
Mint res = lhs;
res *= rhs;
return res;
}
friend Mint operator+(const Mint &lhs, const Mint &rhs) {
Mint res = lhs;
res += rhs;
return res;
}
friend Mint operator-(const Mint &lhs, const Mint &rhs) {
Mint res = lhs;
res -= rhs;
return res;
}
friend Mint operator/(const Mint &lhs, const Mint &rhs) {
Mint res = lhs;
res /= rhs;
return res;
}
friend istream &operator>>(istream &is, Mint &a) {
LL v;
is >> v;
a = Mint(v);
return is;
}
friend ostream &operator<<(ostream &os, const Mint &a) {
return os << a.val();
}
} ;
const int MN = 5;
struct Matrix {
int n, m;
Mint v[MN][MN];
Matrix (int t = 0) {
memset(v, 0, sizeof v);
if(t == 1) {
for(int i = 0; i <= n + 1; i ++)
v[i][i] = 1;
}
}
Matrix operator*(const Matrix& b) const {
Matrix res;
res.n = n, res.m = b.m;
for(int k = 1; k <= m; k ++)
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= b.m; j ++)
res.v[i][j] += this->v[i][k] * b.v[k][j];
return res;
}
Matrix operator^(LL b) {
Matrix res = *this, a = *this;
b --;
while(b) {
if(b & 1) res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
} ;
void solve() {
while(cin >> n >> MOD) {
if(n == 1) {
cout << 1 << endl;
continue;
}
Matrix a, base;
a.n = 1, a.m = 2;
a.v[1][1] = 0, a.v[1][2] = 2;
base.n = 2, base.m = 2;
base.v[1][1] = 4, base.v[1][2] = 0;
base.v[2][1] = 1, base.v[2][2] = 1;
a = a * (base^(n/2));
if(n % 2 == 0) cout << a.v[1][1] << endl;
else if(n % 2 == 1) cout << a.v[1][1] * 2 + 1 << endl;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int t = 1;
//cin >> t;
while(t --) solve();
return 0;
}