返回顶部

有理数类封装

上一版运算过程中会炸

inline int absl(int x){return x>0?x:~x+1;}
inline int min(int x,int y){return x<y?x:y;}
struct rea{
    int mu,zi;
    rea jian(){
        int gcd=__gcd(absl(zi),absl(mu));
        if(mu<0){mu*=-1;zi*=-1;}
        if(!zi){mu=1;return *this;}
        if(!gcd)return *this;
        zi/=gcd;mu/=gcd;
        return *this;
    }
    rea(int x=0,int y=1){zi=x,mu=y;jian();}
    rea dao(){return rea(mu,zi);}
    rea operator+(rea a){return (rea(zi*a.mu+mu*a.zi,mu*a.mu)).jian();}
    rea operator*(rea a){
        int gcd1=__gcd(zi,a.mu);
        int gcd2=__gcd(a.zi,mu);
        return (rea((zi/gcd1)*(a.zi/gcd2),(mu/gcd2)*(a.mu/gcd1))).jian();
    }
    rea operator/(rea a){return (*this*a.dao()).jian();}
    rea operator-(){return rea(-zi,mu);}
    rea operator-(rea a){return *this+(-a);}
    bool operator<(rea a){return zi*a.mu<a.zi*mu;}
    bool operator>(rea a){return !(*this<a);}
    bool operator==(rea a){return !((*this<a)||(*this>a));}
    void out(){
        jian();
        print(zi),putchar_unlocked('/');
        print(mu);putchar_unlocked('\n');
    }
};
inline rea minrea(rea x,rea y){return x<y?x:y;}
posted @ 2024-09-25 16:07  无敌の暗黑魔王  阅读(36)  评论(0编辑  收藏  举报