#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int cnt = 0, f = 1;
  char c = getchar();
  while (!isdigit(c)) {
    if (c == '-') f = -f;
    c = getchar();
  }
  while (isdigit(c)) {
    cnt = (cnt << 3) + (cnt << 1) + c - '0';
    c = getchar();
  }
  return cnt * f;
}
long long n, m, ans;
int main() {
  cin >> n >> m;
  while (n != 1) {
    ans += n / m;
    n %= m;
    if (!n) break;
    swap(n, m);
  }
  if (n == 1) ans += m;
  cout << ans;
  return 0;
}
