1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| #include<cstdio> #include<algorithm> using namespace std;
struct Frac { int up,down; };
int gcd(int a,int b) { return !b?a:gcd(b,a%b); }
void reduction(Frac &a) { if(a.down<0) { a.up=-a.up; a.down=-a.down; } if(a.up==0) a.down=1; else { int factor=gcd(abs(a.up),abs(a.down)); a.up/=factor; a.down/=factor; } }
Frac add(Frac a,Frac b) { Frac ans; ans.down=a.down*b.down; ans.up=a.up*b.down+b.up*a.down; reduction(ans); return ans; }
Frac sub(Frac a,Frac b) { Frac ans; ans.down=a.down*b.down; ans.up=a.up*b.down-b.up*a.down; reduction(ans); return ans; }
Frac multiply(Frac a,Frac b) { Frac ans; ans.up=a.up*b.up; ans.down=a.down*b.down; reduction(ans); return ans; }
Frac divide(Frac a,Frac b) { Frac ans; ans.up=a.up*b.down; ans.down=a.down*b.up; reduction(ans); return ans; }
void print(Frac a) { if(a.down==1) printf("%d",a.up); else if(abs(a.up)>a.down) printf("%d %d/%d",a.up/a.down,abs(a.up)%a.down,a.down); else printf("%d/%d",a.up,a.down); printf("\n"); }
int main() { Frac a,b; a.up=-4; a.down=2; b.up=4; b.down=-6; print(add(a,b)); print(sub(a,b)); print(multiply(a,b)); print(divide(a,b)); return 0; }
|