gcd(A,B)=1,考虑什么时候不再减去1,假设为d,那么有 d|(A-t),d|(B-t),于是有 A = i ∗ d + t A = i*d+t A=i∗d+t, B = j ∗ d + t B = j*d+t B=j∗d+t, 1 ≤ t < d 1\le t <d 1≤t<d, d有以下性质 d 是质数且 d ∣ ( A − B ) d 是质数 且 d| (A-B) d是质数且d∣(A−B)
每次求 A − B A-B A−B的所有质因子
#include<bits/stdc++.h>usingnamespace std;typedeflonglong LL;
LL gcd(LL a,LL b){return b ==0?a:gcd(b,a%b);}voidget(LL a,LL b,LL &ans){if(a ==0||b ==0)return;if(a > b)swap(a,b);LL _min = a;LL d = a;LL t =abs(a-b);LL tmp = t;vector<LL> prime;for(LL i =2;i * i <= tmp;++i){if(t %i ==0){prime.push_back(i);while(t%i==0) t/= i;}}if(t >1) prime.push_back(t);for(auto&c:prime){if(a > c &&a%c < _min){_min = a%c;d = c;}}ans += _min;get((a-_min)/d,(b-_min)/d,ans);}intmain(void){LL A,B;cin>>A>>B;LL d =gcd(A,B);A = A/d;B = B/d;LL ans =0;get(A,B,ans);cout<<ans<<endl;return0;}