1081. Rational Sum (20)

来源:互联网 发布:安卓汉化软件 编辑:程序博客网 时间:2024/05/29 09:15

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:
52/5 4/15 1/30 -2/60 8/3
Sample Output 1:
3 1/3
Sample Input 2:
24/3 2/3
Sample Output 2:
2
Sample Input 3:
31/3 -1/6 1/8
Sample Output 3:
7/24

#include<iostream>#include<cstdio>#include<cmath>using namespace std;int gcd(int a,int b){    while(b!=0)    {        int t=a%b;        a=b;        b=t;    }    return a;}int main(){    int n,suma,sumb,a,b,t;    scanf("%d",&n);    suma=0,sumb=1;    for(int i=0;i<n;i++)    {        scanf("%d/%d",&a,&b);        suma=suma*b+sumb*a;        sumb=sumb*b;        t=gcd(sumb,suma);        suma/=t;        sumb/=t;    }    int p=suma/sumb;    suma%=sumb;    if (suma*sumb<0)    {        suma=-(fabs(suma));        sumb=(fabs(sumb));    }    if (p==0&&suma==0) printf("0");    else if (p==0&&suma!=0) printf("%d/%d",suma,sumb);    else if (p!=0&&suma==0) printf("%d",p);    else printf("%d %d/%d",p,suma,sumb);    return 0;}
原创粉丝点击