分数运算

  1. 分数加减乘除。
  2. 注意精度。
  3. 注意求最大公约数时的大小关系。
int gcd(int m, int n)//m > n
{
    while(n != 0)
    {
        int temp = m % n;
        m = n;
        n = temp;
    }
    return m;
}

int lcm(int a, int b)
{
    return a / gcd(a,b) * b;
}

void fraction_reduction(int &ansX,int &ansY)//y is denominator,x is numerator
{
    int g,kx = 0,ky = 0;//the k is mark whether x||y is positive

    if(ansY == 0 || ansX == 0)
        return;

    if(ansX < 0)
    {
        kx = 1;
        ansX -= ansX<<1;
    }
    if(ansY < 0)
    {
        ky = 1;
        ansY -= ansY<<1;
    }


    if(ansX > ansY)
        g = gcd(ansX,ansY);
    else
        g = gcd(ansY,ansX);
    ansX /= g;
    ansY /= g;

    if(kx == 1)
        ansX -= ansX<<1;
    if(ky == 1)
        ansY -= ansY<<1;
}

void fraction_add(int x1,int y1,int x2,int y2, int &ansX,int &ansY)//y is denominator,x is numerator
{
    if(y1 > y2)
        ansY = lcm(y1,y2);
    else
        ansY = lcm(y2,y1);
    ansX = ansY/y1*x1 + ansY/y2*x2;
    fraction_reduction(ansX,ansY);
}

void fraction_sub(int x1,int y1,int x2,int y2, int &ansX,int &ansY)
{
    if(y1 > y2)
        ansY = lcm(y1,y2);
    else
        ansY = lcm(y2,y1);
    ansX = ansY/y1*x1 - ansY/y2*x2;
    fraction_reduction(ansX,ansY);
}

void fraction_mul(int x1,int y1,int x2,int y2, int &ansX,int &ansY)
{//the precision is limited,so if you use it,you may use long long
    ansX = x1*x2;
    ansY = y1*y2;

    fraction_reduction(ansX,ansY);
}

void fraction_division(int x1,int y1,int x2,int y2, int &ansX,int &ansY)
{
    ansX = x1*y2;
    ansY = x2*y1;

    fraction_reduction(ansX,ansY);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值