/** * @FileName a.cpp * @Author kanpurin * @Created 2022.05.14 19:52:20 **/ #include "bits/stdc++.h" using namespace std; typedef long long ll; template T extgcd(T a, T b, T &x, T &y) { if (b == 0) { x = 1; y = 0; return a; } T d = extgcd(b, a%b, y, x); y -= a / b * x; return d; } ll solveL(int p,int q) { int x,y; int g = extgcd(p,-q,x,y); if (g < 0) x = -x, y = -y; if (x < 0 || y < 0) x += q, y += p; return x+y; } ll solveR(int p,int q) { int x,y; int g = extgcd(-p,q,x,y); if (g < 0) x = -x, y = -y; if (x < 0 || y < 0) x += q, y += p; return x+y; } int main() { int p,q;cin >> p >> q; cout << solveL(p,q) + solveR(p,q) << endl; return 0; }