1088 Rational Arithmetic

problem 1088 Rational Arithmetic
partial same as 1081 Rational Sum

#include<iostream>
#include<cmath>
using namespace std;
#pragma warning(disable:4996)
long long gcd(long long a, long long b) {
    return b == 0 ? a : gcd(b, a % b);
}
struct Num {
    long long n, d, i = 0;
    void print();
    void simple();
};
void Num::print() {
    if (d == 0)cout << "Inf";
    else if (n < 0) {
        if (n % d == 0)
            cout << "(" << n / d << ")";
        else if (-n > d)
            cout << "(" << n / d << " " << -n % d << "/" << d << ")";
        else
            cout << "(" << n << "/" << d << ")";
    }
    else {
        if (n % d == 0)
            cout << n / d;
        else if (n > d)
            cout << n / d << " " << n % d << "/" << d;
        else
            cout << n << "/" << d;
    }
}
void Num::simple() {
    if (d < 0) {
        d = -d;
        n = -n;
    }
    if (n == 0)
        d = 1;
    else {
        int x = gcd(abs(n), abs(d));
        n /= x;
        d /= x;
    }
}
Num add(Num a, Num b) {
    Num* res = new Num;
    res->d = a.d * b.d;
    res->n = a.d * b.n + a.n * b.d;
    res->simple();
    return *res;
}
Num mul(Num a, Num b) {
    Num* res = new Num;
    res->n = a.n * b.n;
    res->d = a.d * b.d;
    res->simple();
    return *res;
}
int main(){
    Num a, b;
    scanf("%lld/%lld %lld/%lld", &a.n, &a.d, &b.n, &b.d);
    a.simple();
    b.simple();
    a.print(); cout << " + "; b.print(); cout << " = "; add(a, b).print(); cout << endl;
    Num b1 = b;
    b1.n = -b1.n;
    a.print(); cout << " - "; b.print(); cout << " = "; add(a, b1).print(); cout << endl;
    a.print(); cout << " * "; b.print(); cout << " = "; mul(a, b).print(); cout << endl;
    Num b2 = b;
    swap(b2.d, b2.n);
    a.print(); cout << " / "; b.print(); cout << " = "; mul(a, b2).print(); cout << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值