[类欧几里得算法 数论] BZOJ 2187 fraction

应该也是个变形

%%%Vani


#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> abcd;

inline char nc(){
	static char buf[100000],*p1=buf,*p2=buf;
	if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
	return *p1++;
}
inline int read(ll &x)
{
	char c=nc(),b=1;
	for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1; else if (c==EOF) return 0;
	for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b; return 1;
}

ll gcd(ll a, ll b) {
	return !b?a:gcd(b,a%b);
}

abcd Solve(ll p1,ll q1,ll p2,ll q2) {
	ll l=(ll)floor((double)p1/q1)+1,r=(ll)ceil((double)p2/q2)-1;
	abcd ret;
	if (l<=r)
		return abcd(l,1);
	if (p1==0)
		return abcd(1,(ll)floor((double)q2/p2)+1);
	if (p1<=q1 && p2<=q2){
		ret=Solve(q2,p2,q1,p1);
		swap(ret.first,ret.second);
		return ret;
	}
	ll t=p1/q1;
	ret=Solve(p1-q1*t,q1,p2-q2*t,q2);
	ret.first+=ret.second*t;
	return ret;
}

int main(){
	ll a,b,c,d,t; abcd ans;
	freopen("t.in","r",stdin);
	freopen("t.out","w",stdout);
	while (read(a) && read(b) && read(c) && read(d)){
		t=gcd(a,b),a/=t,b/=t;
		t=gcd(c,d),c/=t,d/=t;
		ans=Solve(a,b,c,d);
		printf("%lld/%lld\n",ans.first,ans.second);
	}
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值