codeforces 710D Two Arithmetic Progressions

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;
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值