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
思路:先不管真分数假分数,每次分数相加直接通分得出结果,最后再将结果化成带分数的形式。注意的是,在每次相加的过程中,如果中间结果可以化简,就必须化简,不然会超时。也要主要分母为0的情况。
代码:
#include <iostream> #include <cstdio> #include <cmath> using namespace std; int gcd(int a, int b) { if(a < b) { int tmp = a; a = b; b = tmp; } if(b == 0) return a; else return gcd(b,a%b); } int main() { int n; scanf("%d",&n); long long pre_num = 0; long long pre_den = 0; long long temp1; long long temp2; for(int i = 0; i < n ; i++) { long int a,b; scanf("%ld/%ld",&a,&b); if(i == 0) { pre_num = a; pre_den = b; int k = gcd(abs(a),abs(b)); if(k != 0) { pre_num /= k; pre_den /= k; } } else { temp1 = pre_num; temp2 = pre_den; pre_num = temp1 * b + temp2 * a; pre_den = temp2 * b; int k = gcd(abs(pre_num),abs(pre_den)); if(k != 0) { pre_num /= k; pre_den /= k; } } } if(pre_num == 0) { printf("0\n"); return 0; } if(pre_num / pre_den > 0) { if(pre_num % pre_den == 0) { printf("%ld",pre_num / pre_den); } else printf("%ld ",pre_num / pre_den); } else if(pre_num / pre_den < 0) { if(pre_num % pre_den == 0) { printf("%ld",pre_num / pre_den); } else printf("%ld ",pre_num / pre_den); pre_num = abs(pre_num); pre_den = abs(pre_den); } long int x = pre_num - pre_num / pre_den * pre_den; long int y = pre_den; if(x != 0) { int k = gcd(x,y); printf("%ld/%ld\n",x/k,y/k); } else printf("\n"); return 0; }