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
41
42
43
44
45
46
47
48
#include <bits/stdc++.h>
using namespace std;

typedef long long int lli;

vector<int> v;

lli solve(int a, int b) {
    if (a > b)
        return solve(b, a);
    
    if (a == 0)
        return 0;
    
    int usei = 0;
    
    for (int i=0; i<(int)v.size(); i++) {
        if (v[i] <= a)
            usei = i;
        else
            break;
    }
    
    lli bar_cost = a / v[usei] + solve(a % v[usei], v[usei]);
    
    return bar_cost * (b / v[usei]) + solve(b % v[usei], a);
}

int main() {
    int a, b;
    scanf("%d%d", &a, &b);
    int n;
    scanf("%d", &n);
    
    for (int i=0; i<n; i++) {
        int x;
        scanf("%d", &x);
        v.push_back(x);
    }
    
    if (a % v[0] != 0 || b % v[0] != 0) {
        printf("-1\n");
        return 0;
    }
    
    printf("%lld\n", solve(a, b));
    return 0;
}