#include typedef long long ll; using namespace std; int INF = 1LL << 30; int MOD = 1e9+7; int gcd (int a,int b){ return b ? gcd(b,a%b) : a; } main(){ int M,N; cin >> M >> N; int g = gcd(M,N); M /= g, N /= g; ll cnt = 0; while(N != 1){ if(M > N){ cnt += M / N; M -= (M / N) * N; }else{ swap(M,N); cnt++; } } cnt += M-1; cout << cnt << endl; }