#include <bits/stdc++.h>
using namespace std;
int ar[100004];
char str[100004];
int main() {
  long long a, b;
  cin >> a >> b;
  long long ans = 0;
  if (b == 1) {
    cout << a << "\n";
    return 0;
  }
  if (a > b) {
    long long x = a / b;
    ans = x;
    a = a - (x * b);
    b = b;
  }
  long long atemp;
  while (a > 1) {
    atemp = a;
    a = b - a;
    b = atemp;
    if (a > b) {
      long long x = a / b;
      ans = ans + x;
      a = a - (x * b);
      b = b;
    }
    ans++;
  }
  ans += b;
  cout << ans;
  return 0;
}
