#include <iostream>
#include <fstream>
using namespace std;
int a, b, x, y;
int extgcd(int a, int b,int &x, int &y){
int d = a;
if(b != 0){
d = extgcd(b, a % b, y, x);
y -= (a / b) * x;
}
else x = 1, y = 0;
return d;
}
int main(){
fstream in("mod.in", ios::in), out("mod.out", ios::out);
in >> a >> b;
extgcd(a, b, x, y);
while(x < 0) x += b;
x %= b;
out << x << endl;
return 0;
}