#include int gcd(int a, int b) { if (a == 0) return b; else return gcd(b % a, a); } int main() { int P, Q, p[2], q[2], g; long long tmp; scanf("%d %d", &P, &Q); for (p[0] = 1; p[0] * 2 <= P; p[0]++) { tmp = (long long)p[0] * Q; g = tmp % P; if (g == 1) { q[0] = (tmp - 1) / P; break; } else if (g == P - 1) { q[0] = (tmp + 1) / P; break; } } p[1] = P - p[0]; q[1] = Q - q[0]; g = gcd(p[1], q[1]); p[1] /= g; q[1] /= g; printf("%d\n", p[0] + q[0] + p[1] + q[1]); fflush(stdout); return 0; }