#include<iostream>
#include<iomanip>
#include<algorithm>
#include<array>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<functional>
#include<limits>
#include<list>
#include<map>
#include<numeric>
#include<set>
#include<stack>
#include<string>
#include<sstream>
#include<queue>
#include<vector>
using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

#define dump(o) { cerr << #o << " " << o << endl; }
#define dumpc(o) { cerr << #o; for (auto &e : (o)) cerr << " " << e; cerr << endl; }
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3fLL

vector<long long> a;
vector<long long> b;

long long cnt = 0;

//最大公約数
long long gcd(long long x, long long y) {
	if (y) {
		cnt++;
		a.push_back(y);
		b.push_back(x / y);
		return gcd(y, x%y);
	}
	else {
		return x;
	}
}

long long main() {
	long long N, K; cin >> N >> K;
	K = max(N - K, K);
	gcd(N, K);
	long long ans;
	if (cnt == 1) {
		ans = a[0] * 3;
	}
	else if (cnt == 2) {
		ans = 1 * a[0];
		ans += (2 * b[1])*a[1];
	}
	else {
		ans = 1 * a[0];
		ans += (2 * b[1] + 1)*a[1];
		for (long long i = 2; i < a.size() - 1; i++) {
			ans += 2 * b[i] * a[i];
			//dump(ans);
		}
		ans += (2 * b[a.size() - 1] - 1)*a[a.size() - 1];
		//dumpc(a);
		//dumpc(b);
	}
	//cout << cnt << endl;
	cout << ans << endl;

	return 0;
}