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/3Sample Output 1:
3 1/3Sample Input 2:
2 4/3 2/3Sample Output 2:
2Sample Input 3:
3 1/3 -1/6 1/8Sample Output 3:
7/24
#include <iostream>#include <stdio.h>#include <algorithm>#include <vector>#include <math.h>#pragma warning(disable:4996)using namespace std;long long int GongYue(long long int a, long long int b) {if (a == 0 || b == 0)return 1;if (a == b)return b;else if (a > b) {int m = a%b;while (m != 0) {a = b;b = m;m = a%b;}return b;}else {int m = b%a;while (m != 0) {b = a;a = m;m = b%a;}return a;}}vector<long long int> fenzi, fenmu;int main(void) {int n;cin >> n;char temp[50];long long int fenzi4push,fenmu4push;for (int i = 0; i < n; i++) {scanf("%s", temp);sscanf(temp, "%lld/%lld", &fenzi4push, &fenmu4push);if (fenzi4push == 0)continue;long long int yuefen = GongYue(abs(fenzi4push), abs(fenmu4push));fenzi4push /= yuefen;fenmu4push /= yuefen;fenzi.push_back(fenzi4push);fenmu.push_back(fenmu4push);}n = fenzi.size();if (fenzi.size() == 0) {cout << "0";return 0;}long long int fenziResult=fenzi[0], fenmuResult=fenmu[0];for (int i = 1; i < n; i++) {if (fenmuResult == fenmu[i]) {fenziResult += fenzi[i];long long int yueshu = GongYue(abs(fenmuResult), abs(fenziResult));fenziResult /= yueshu;fenmuResult /= yueshu;}else {fenziResult = fenziResult*fenmu[i]+fenmuResult*fenzi[i];fenmuResult = fenmuResult*fenmu[i];long long int yueshu = GongYue(abs(fenmuResult), abs(fenziResult));fenziResult /= yueshu;fenmuResult /= yueshu;}}if (fenziResult*fenmuResult<0) {fenziResult = abs(fenziResult);fenmuResult = abs(fenmuResult);cout << "-";}if (fenziResult % fenmuResult == 0)cout << fenziResult / fenmuResult;else if (fenziResult > fenmuResult)cout << fenziResult / fenmuResult << " " << fenziResult % fenmuResult << "/" << fenmuResult;elsecout << fenziResult << "/" << fenmuResult;return 0;}
原文:http://www.cnblogs.com/zzandliz/p/5023260.html