PAT:A1081 Rational Sum (20 分)
Given N rational numbers in the form numerator/denominator
, you are supposed to calculate their sum.
Input Specification:
Each input file contains one test case. Each case starts with a positive integer N (≤100), followed in the next line N rational numbers a1/b1 a2/b2 ...
where all the numerators and denominators are in the range of long int. If there is a negative number, then the sign must appear in front of the numerator.
Output Specification:
For each test case, output the sum in the simplest form integer numerator/denominator
where integer
is the integer part of the sum, numerator
< denominator
, and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.
Sample Input 1:
5
2/5 4/15 1/30 -2/60 8/3
Sample Output 1:
3 1/3
Sample Input 2:
2
4/3 2/3
Sample Output 2:
2
Sample Input 3:
3
1/3 -1/6 1/8
Sample Output 3:
7/24
代码:
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
// 本题用到了分数的加减,化简,寻找公约数, 分子的输出
int gcd(ll a, ll b) {
if(b == 0) return a;
else return gcd(b, a%b);
}
// 分数的构造体
struct Fraction{
long long up, down;
};
// 分数的化简
Fraction reduction(Fraction r) {
if(r.down < 0) {
r.up = -r.up;
r.down = -r.down;
}
if(r.up == 0) r.down = 1;
else {
ll d = gcd(abs(r.up), abs(r.down));
r.up = r.up / d;
r.down = r.down / d;
}
return r;
}
// 分数的加法
Fraction add(Fraction a, Fraction b) {
a = reduction(a), b = reduction(b);
Fraction c;
c.down = a.down * b.down;
c.up = a.up * b.down + a.down * b.up;
return reduction(c);
}
// 分数的减法
Fraction sub(Fraction a, Fraction b) {
a = reduction(a), b = reduction(b);
Fraction c;
c.down = a.down * b.down;
c.up = a.up * b.down - a.down * b.up;
return reduction(c);
}
// 分数的输出
void printFra(Fraction r) {
r = reduction(r);
if(r.down == 1) printf("%lld", r.up);
else if(r.up > r.down) printf("%lld %lld/%lld", r.up/r.down, r.up%r.down, r.down);
else {
printf("%lld/%lld", r.up, r.down);
}
}
int main() {
int N;
Fraction a, sum;
sum.up = 0, sum.down = 0;
scanf("%d", &N);
for(int i = 0; i < N; i++) {
scanf("%lld/%lld", &a.up, &a.down);
sum = add(sum, a);
}
printFra(sum);
return 0;
}