最大公约数、最小公倍数和分数四则运算模板

6 篇文章 0 订阅
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
const int Maxn = 2020;

struct Fraction //分数结构体
{
    int up,down;
};

int gcd(int a,int b) //最大公约数模板 a>b
{
    if(b == 0) return a;  
    else return gcd(b,a%b);
}

int lcm(int a,int b) //最小公倍数模板
{
    int d = gcd(a,b); //得到最大公约数d
    return a * b / d; // 也可以通过(a / d * b)防止溢出
}

Fraction reduction(Fraction f)
{
    if(f.down < 0) //如果分母为负数就让分子分母变成其相反数,保证格式统一
    {
        f.down = - f.down;
        f.up = - f.up;
    }
    if(f.up == 0)
    {
        f.down = 1; //如果分子为0就让分母为1
    }
    else
    {
        int d = gcd(abs(f.up),abs(f.down)); //约分
        f.up /= d;
        f.down /= d;
    }
    return f;
}

Fraction add(Fraction f1,Fraction f2) //加法
{
    Fraction f;
    f.up = f1.up * f2.down + f1.down * f2.up;
    f.down = f1.down * f2.down;
    return reduction(f);
}

Fraction sub(Fraction f1,Fraction f2) //减法
{
    Fraction f;
    f.up = f1.up * f2.down - f1.down * f2.up;
    f.down = f1.down * f2.down;
    return reduction(f);
}

Fraction mul(Fraction f1,Fraction f2) //乘法
{
    Fraction f;
    f.up = f1.up * f2.up;
    f.down = f1.down * f2.down;
    return reduction(f);
}

Fraction div(Fraction f1,Fraction f2)  //除法,除数f2不能为零!f2.up != 0
{
    Fraction f;
    f.up = f1.up * f2.down;
    f.down = f1.down * f2.up;    
    return reduction(f);
}


int main()
{
    freopen("1.txt","r",stdin);
    int a,b,c;
    cin>>a>>b;
    c = gcd(a,b);
    cout<<c;

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值