类欧几里得算法
日常上板子:link
例题
函数
习题
1
Fraction\
诶我小学不做出来过吗\
给定
#include<bits/stdc++.h>
using namespace std;
void solve(int a,int b,int&p,int&q,int c,int d){
if(a<b&&c>d){
p=q=1;
return;
}
solve(d%c,c,q,p,b-a*(d/c),a);
q+=(d/c)*p;
return;
}
int main(){
int a,b,c,d,p,q;
while(cin>>a>>b>>c>>d){
solve(a,b,p,q,c,d);
cout<<p<<"/"<<q<<endl;
}
return 0;
}
T2
link
就是和T1读入方式不同。。\ 为了证明和T1没区别,另开read()函数\ 特判0的情况,不然90pts\ code:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve(ll a,ll b,ll&p,ll&q,ll c,ll d){
if(a<b&&c>d){
p=q=1;
return;
}
solve(d%c,c,q,p,b-a*(d/c),a);
q+=(d/c)*p;
return;
}
int num;
void read(ll &a,ll &b,ll &c,ll &d){
char ch;ll x=1,y=0;
cin>>ch>>ch;
for(int i=1;i<=num;i++){
cin>>ch;
x*=10;
y=y*10+ch-'0';
}
if(y==0){
a=-2;return;
}
b=d=x*2;
a=y*2-1;c=y*2+1;
ll ab=__gcd(a,b);a/=ab,b/=ab;
ll cd=__gcd(c,d);c/=cd,d/=cd;
}
int main(){
ll a,b,c,d,p,q;
while(cin>>num){
read(a,b,c,d);
if(a==-2){
cout<<1<<endl;
continue;
}
solve(a,b,p,q,c,d);
cout<<min(b,q)<<endl;
}
return 0;
}