#include <iostream>
using namespace std;
int inv(int a,int p){
if(a == 1) return 1;
return inv(p%a,p)*(p-p/a)%p;
}
int main()
{
int p,a;
while(cin >> a >> p){
cout << inv(a,p);
}
return 0;
}
#include <iostream>
using namespace std;
int inv(int a,int p){
if(a == 1) return 1;
return inv(p%a,p)*(p-p/a)%p;
}
int main()
{
int p,a;
while(cin >> a >> p){
cout << inv(a,p);
}
return 0;
}