#include <bits/stdc++.h>
using namespace std;
long long power(long x, long n) {
  if (n == 0) return 1;
  if (n == 1) return x;
  long n2 = n / 2;
  long long po = power(x, n2);
  if (n % 2) return po * po * x;
  return po * po;
}
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  a %= b;
  return gcd(b, a);
}
class CRationalResistance {
 public:
  void solve(std::istream &cin, std::ostream &cout) {
    long long a, b, c = 0, t;
    cin >> a >> b;
    while (a && b) {
      if (a == 1 || b - 1 == a) {
        c += b;
        break;
      }
      if (b > a) {
        t = b - a;
        b = a;
        a = t;
        c++;
      } else {
        c += a / b;
        a %= b;
      }
    }
    cout << c << '\n';
  }
};
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0);
  CRationalResistance solver;
  std::istream &in(std::cin);
  std::ostream &out(std::cout);
  solver.solve(in, out);
  return 0;
}
