#include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
const int INF = int(2e9);
const long long LINF = long long(2e9) * long long(2e9);
template <class T, class C>
void chmax(T& a, C b) {
  a > b ?: a = b;
}
template <class T, class C>
void chmin(T& a, C b) {
  a < b ?: a = b;
}
bool is_first = true;
long long func(long long X, long long Z) {
  long long a;
  if (is_first == true)
    a = X / Z;
  else
    a = (X - Z) / Z;
  is_first = false;
  long long X2 = X % Z;
  long long ret = X + Z + 2 * a * Z + X2;
  if (X2 == 0) {
    return ret;
  }
  long long Z2 = Z - X2;
  return ret + func(X2, Z2);
}
int main() {
  long long X, N;
  cin >> N >> X;
  cout << func(X, N - X) << endl;
  return 0;
}
