结构体实现,仅有一些简单功能。
struct frac{
int m,z;
void clear(){m=0,z=0;}
friend frac operator+(frac a,frac b){
if(!a.m) return b;if(!b.m) return a;
frac res;
int l=a.m*b.m/gcd(a.m,b.m);res.m=l,res.z=a.z*(l/a.m)+b.z*(l/b.m);
int g=gcd(res.m,res.z);res.m/=g,res.z/=g;
return res;
}
friend frac operator-(frac a,frac b){
if(!a.m) return b;if(!b.m) return a;
frac res;
int l=a.m*b.m/gcd(a.m,b.m);res.m=l,res.z=a.z*(l/a.m)-b.z*(l/b.m);
int g=gcd(res.m,res.z);res.m/=g,res.z/=g;
return res;
}
friend frac operator*(frac a,frac b){
if(!a.m||!b.m) return {0,0};
frac res;
res.m=a.m*b.m,res.z=a.z*b.z;
int g=gcd(res.m,res.z);res.m/=g,res.z/=g;
return res;
}
friend frac operator/(frac a,frac b){
if(!a.m||!b.m) return {0,0};
frac res,_b={b.z,b.m};
res.m=a.m*_b.m,res.z=a.z*_b.z;
int g=gcd(res.m,res.z);res.m/=g,res.z/=g;
return res;
}
friend bool operator<(frac a,frac b){
frac res=a-b;
if(res.m*res.z<0) return true;
return false;
}
friend bool operator>(frac a,frac b){
frac res=a-b;
if(res.m*res.z<0) return false;
return true;
}
friend bool operator==(frac a,frac b){
frac res=a-b;
return res.z==0;
}
friend bool operator!=(frac a,frac b){
frac res=a-b;
return res.z!=0;
}
}