1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
ll arr[50], out;
void solve(ll a, ll b){
	if(a==0 || b==0) return;
	ll tmp=a, cur=-1, cnt=0;
	while(tmp>0){
		for(int i=n-1; i>=0; i--){
			if(arr[i]<=tmp){
				ll ofs=tmp/arr[i];
				tmp-=arr[i]*ofs;
				if(cur==-1) cur=arr[i];
				cnt+=cur/arr[i]*ofs;
				break;
			}
		}
	}
	cnt*=b/cur;
	out+=cnt;
	b%=cur;
	solve(b, a);
}
int main(){
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	ll a, b;
	cin >> a >> b;
	if(a>b) swap(a, b);
	cin >> n;
	for(int i=0; i<n; i++) cin >> arr[i];
	if(a%arr[0]!=0 || b%arr[0]!=0){
		cout << -1 << '\n';
		return 0;
	}
	solve(a, b);
	cout << out << '\n';
	return 0;
}