#include <iostream>
#define N_MAX 50

typedef long long LL;
using namespace std;

int gcd(int a, int b)
{
	int c;
	while (a != 0)
	{
		c = a;
		a = b%a;
		b = c;
	}
	return b;
}

int main()
{
	int N, M;
	cin >> M >> N;
	int ans = 0;

	int g = gcd(M, N);
	M /= g;
	N /= g;

	while (N != 1 || M != 1)
	{
		//逆数へ
		if (M < N)
		{
			swap(N, M);
			++ans;
		}

		if (N == 1)
		{
			//面倒だから
			ans += M-1;
			break;
		}
		int t = M / N;
		ans += t;
		M -= t * N;
	}

	cout << ans << endl;

	return 0;
}