You are given two arithmetic progressions: a1k + b1 and a2l + b2. Find the number of integers x such that L ≤ x ≤ R andx = a1k' + b1 = a2l' + b2, for some integers k', l' ≥ 0.
Input
The only line contains six integers a1, b1, a2, b2, L, R (0 < a1, a2 ≤ 2·109, - 2·109 ≤ b1, b2, L, R ≤ 2·109, L ≤ R).
Output
Print the desired number of integers x.
拓展欧几里得算法,a1k' + b1 = a2l' + b2 ,即a1*k-a2*l=b2-b1;这个就是赤裸裸的欧几里得算法。可
以求出一连串的k,接下来筛出k大于等于0的,带入得到x,再从这里面选出x能让l大于等于零的才是最终的答案;
AC代码:
# include <iostream>
# include <math.h>
# include <stdlib.h>
using namespace std;
typedef long long int ll;
ll gcd(ll a, ll b){
if(a%b==0){
return b;
}
return gcd(b, a%b);
}
void ex_gcd(ll a, ll b, ll &x, ll &y ){
if(!b){
x=1;y=0;
}
else{
ex_gcd(b, a%b, y, x);
y-=x*(a/b);
}
}
int main(){
ll a1, a2, b1, b2, L, R, a, b, c, g, x, y, _b, lcm, begin;
ll l, r;
cin>>a1>>b1>>a2>>b2>>L>>R;
a=a1;b=-a2;c=b2-b1;
g=gcd(a, b);
if(c%g!=0){
cout<<0;
return 0;
}
ex_gcd(a, b, x, y);
x=x*c/g;y=y*c/g;
_b=abs(b/g);
if((L-b1)%a1==0)l=(L-b1)/a1;
else l=(L-b1)<0?(L-b1)/a1:(L-b1)/a1+1;
if((R-b1)%a1==0)r=(R-b1)/a1;
else r=(R-b1)<0?(R-b1)/a1-1:(R-b1)/a1;
if(r<0){cout<<0;return 0;}
else if(l<0){l=0;}
if((l-x)%_b==0)L=(l-x)/_b;
else L=(l-x)<0?(l-x)/_b:(l-x)/_b+1;
if((r-x)%_b==0)R=(r-x)/_b;
else R=(r-x)<0?(r-x)/_b-1:(r-x)/_b;
if(R<L) cout<<0;
else {
ll cnt=R-L+1;
lcm=a1*a2/gcd(a1, a2);
if(a1*(x+L*_b)+b1>=b2){
cout<<cnt;
}
else{
ll temp=b2-(a1*(x+L*_b)+b1);
if(temp%lcm!=0)
cnt=cnt-temp/lcm-1;
else cnt=cnt-temp/lcm;
if(cnt<=0) cout<<0;
else cout<<cnt;
}
}
return 0;
}