#include <bits/stdc++.h> using namespace std; typedef long long ll; int INT() { int in; scanf("%d", &in); return in; } vector <ll> d; ll solve(ll a, ll b, int i) { if(!b) return 0ll; if(d[i]>b) return solve(a, b, i-1); ll sum=b/d[i]; for(int j=i-1; j>=0; --j) sum+=(d[i]/d[j])*((b%d[j+1])/d[j]); return solve(b, a%d[i], i-1)+(a/d[i])*sum; } int main() { ll a=ll(INT()), b=ll(INT()); int n=INT(); if(a<b) swap(a, b); d.resize(n); for(ll &di : d) di=ll(INT()); if((a%d[0]) || (b%d[0])) printf("-1\n"); else printf("%lld\n", solve(a, b, n-1)); exit(0); }
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 | #include <bits/stdc++.h> using namespace std; typedef long long ll; int INT() { int in; scanf("%d", &in); return in; } vector <ll> d; ll solve(ll a, ll b, int i) { if(!b) return 0ll; if(d[i]>b) return solve(a, b, i-1); ll sum=b/d[i]; for(int j=i-1; j>=0; --j) sum+=(d[i]/d[j])*((b%d[j+1])/d[j]); return solve(b, a%d[i], i-1)+(a/d[i])*sum; } int main() { ll a=ll(INT()), b=ll(INT()); int n=INT(); if(a<b) swap(a, b); d.resize(n); for(ll &di : d) di=ll(INT()); if((a%d[0]) || (b%d[0])) printf("-1\n"); else printf("%lld\n", solve(a, b, n-1)); exit(0); } |