1081 Rational Sum
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.
刚开始有个例子怎么过不去,后来发现是计算最小公倍数的函数返回类型用了int,没有用long long。
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string>
using namespace std;
string temp_num;
long long gcd(long long a, long long b)
{
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
long long lcm(long long a, long long b, long long gcd_num)
{
return a / gcd_num * b;
}
struct info{
int fh;
long long pre;
long long post;
} arr[110];
int main()
{
int num;
cin >> num;
for (int i = 0; i < num; i++) {
cin >> temp_num;
string pre;
string post;
long long post_xg;
if (temp_num[0] == '-') {
arr[i].fh = 0;
post_xg = temp_num.find('/');
pre = temp_num.substr(1, post_xg);
post = temp_num.substr(post_xg + 1, int(temp_num.size()) - post_xg - 1);
} else {
arr[i].fh = 1;
post_xg = temp_num.find('/');
pre = temp_num.substr(0, post_xg);
post = temp_num.substr(post_xg + 1, int(temp_num.size()) - post_xg - 1);
}
arr[i].pre = atoi(pre.c_str());
arr[i].post = atoi(post.c_str());
}
long long temp = arr[0].post;
for (int i = 1; i < num; i++) {
long long temp_2 = gcd(arr[i].post, temp);
temp = lcm(arr[i].post, temp, temp_2);
}
long long pre_num = 0;
for (int i = 0; i < num; i++) {
if (arr[i].fh == 1) {
pre_num += temp / arr[i].post * arr[i].pre;
} else {
pre_num -= temp / arr[i].post * arr[i].pre;
}
}
if (pre_num < 0) {
cout << '-';
pre_num = -pre_num;
}
if (pre_num == 0) {
cout << '0' << endl;
return 0;
}
int flag = 0;
if (pre_num > temp) {
long long r = pre_num / temp;
cout << r;
flag = 1;
}
if (pre_num % temp == 0) {
return 0;
}
if (flag == 1) {
cout << ' ';
}
long long rr = pre_num % temp;
long long t = gcd(rr, temp);
cout << rr / t << '/' << temp / t << endl;
return 0;
}