BZOJ2187:fraction

本文详细介绍了类欧几里得算法的实现原理及应用,通过数学公式展示了算法的具体步骤,包括递归处理和特殊情况的处理。文章还提供了一个C++代码示例,用于求解特定数学问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sol

分情况讨论

  1. ⌊ab⌋+1≤⌈cd⌉−1\lfloor\frac{a}{b}\rfloor+1\le \lceil\frac{c}{d}\rceil-1ba+1dc1
    直接取 q=1,p=⌊ab⌋+1q=1,p=\lfloor\frac{a}{b}\rfloor+1q=1,p=ba+1
  2. a=0a=0a=0
    那么 q>pdcq> \frac{pd}{c}q>cpd
    直接取 p=1,q=⌊dc⌋+1p=1,q=\lfloor\frac{d}{c}\rfloor+1p=1,q=cd+1
  3. a&lt;ba&lt;ba<bc≤dc\le dcd
    那么递归处理 dc&lt;qp&lt;ba\frac{d}{c} &lt; \frac{q}{p} &lt; \frac{b}{a}cd<pq<ab
  4. a≥ba\ge bab
    那么递归处理 a mod bb&lt;pq−⌊ab⌋&lt;cd−⌊ab⌋\frac{a~mod~b}{b} &lt; \frac{p}{q}-\lfloor\frac{a}{b}\rfloor &lt; \frac{c}{d}-\lfloor\frac{a}{b}\rfloorba mod b<qpba<dcba

形式上类似于欧几里得算法,把 (a,b)(a,b)(a,b) 转化成 (a mod b,b)(a~mod~b,b)(a mod b,b) 可能就是是类欧几里得算法的精髓

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;

inline ll Gcd(ll x, ll y) {
	if (!x || !y) return x | y;
	return !y ? x : Gcd(y, x % y);
}

inline void Solve(ll a, ll b, ll c, ll d, ll &x, ll &y) {
	register ll g = Gcd(a, b), nx, ny;
	a /= g, b /= g, g = Gcd(c, d), c /= g, d /= g;
	nx = a / b + 1, ny = c / d + (c % d > 0) - 1;
	if (nx <= ny) x = nx, y = 1;
	else if (!a) x = 1, y = d / c + 1;
	else if (a < b && c <= d) Solve(d, c, b, a, y, x);
	else Solve(a % b, b, c - d * (a / b), d, x, y), x += y * (a / b);
}

ll a, b, c, d, x, y;

int main() {
	while (scanf("%lld%lld%lld%lld", &a, &b, &c, &d) != EOF) Solve(a, b, c, d, x, y), printf("%lld/%lld\n", x, y);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值