#include <bits/stdc++.h>
using namespace std;
int eulerPhi(int X) {
int i = 2;
int q, ret = X;
while (1LL * i * i <= X) {
q = X / i;
if (X == i * q) {
do {
X = q;
q = X / i;
} while (X == i * q);
ret = (ret / i) * (i - 1);
}
i++;
}
if (X != 1) {
ret = ret / X * (X - 1);
}
return ret;
}
int lgPut(int A, int B, int MOD) {
int Q = 1;
while (B) {
if (B & 1) {
Q = (1LL * Q * A) % MOD;
}
A = (1LL * A * A) % MOD;
B >>= 1;
}
return Q;
}
int solve(int A, int MOD) {
if (MOD == 1) {
return 0;
}
if (A == 1) {
return 1;
}
return lgPut(A, solve(A - 1, eulerPhi(MOD)), MOD);
}
int main() {
int N, M;
scanf("%d%d", &N, &M);
printf("%d\n", solve(N, M));
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgZXVsZXJQaGkoaW50IFgpIHsKICAgIGludCBpID0gMjsKICAgIGludCBxLCByZXQgPSBYOwogCiAgICB3aGlsZSAoMUxMICogaSAqIGkgPD0gWCkgewogICAgICAgIHEgPSBYIC8gaTsKIAogICAgICAgIGlmIChYID09IGkgKiBxKSB7CiAgICAgICAgICAgIGRvIHsKICAgICAgICAgICAgICAgIFggPSBxOwogICAgICAgICAgICAgICAgcSA9IFggLyBpOwogICAgICAgICAgICB9IHdoaWxlIChYID09IGkgKiBxKTsKIAogICAgICAgICAgICByZXQgPSAocmV0IC8gaSkgKiAoaSAtIDEpOwogICAgICAgIH0KICAgICAgICBpKys7CiAgICB9CiAKICAgIGlmIChYICE9IDEpIHsKICAgICAgICByZXQgPSByZXQgLyBYICogKFggLSAxKTsKICAgIH0KICAgIHJldHVybiByZXQ7Cn0KIAppbnQgbGdQdXQoaW50IEEsIGludCBCLCBpbnQgTU9EKSB7CiAgICBpbnQgUSA9IDE7CiAgICB3aGlsZSAoQikgewogICAgICAgIGlmIChCICYgMSkgewogICAgICAgICAgICBRID0gKDFMTCAqIFEgKiBBKSAlIE1PRDsKICAgICAgICB9CiAgICAgICAgQSA9ICgxTEwgKiBBICogQSkgJSBNT0Q7CiAgICAgICAgQiA+Pj0gMTsKICAgIH0KICAgIHJldHVybiBROwp9CiAKaW50IHNvbHZlKGludCBBLCBpbnQgTU9EKSB7CiAgICBpZiAoTU9EID09IDEpIHsKICAgICAgICByZXR1cm4gMDsKICAgIH0KICAgIGlmIChBID09IDEpIHsKICAgICAgICByZXR1cm4gMTsKICAgIH0KICAgIHJldHVybiBsZ1B1dChBLCBzb2x2ZShBIC0gMSwgZXVsZXJQaGkoTU9EKSksIE1PRCk7Cn0KCmludCBtYWluKCkgewoJaW50IE4sIE07CglzY2FuZigiJWQlZCIsICZOLCAmTSk7CglwcmludGYoIiVkXG4iLCBzb2x2ZShOLCBNKSk7Cn0=