PAT-A 1081.Rational Sum

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.

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<stdio.h>
long long ans[2]={0,1};
long long factor(long long a,long long b);
void add(long long ans[],long long a1,long long a2,long long b1,long long b2);
void print(long long a,long long b);
int main()
{
    int n;
    long long a,b;
    scanf("%d",&n);
    while(n--){
        scanf("%lld/%lld",&a,&b);
        add(ans,ans[0],ans[1],a,b);
    }
    print(ans[0],ans[1]);
    return 0;
}
long long factor(long long a,long long b)
{
    if(a<0)
        a=-a;
    if(b<0)
        b=-b;
    long long max=a>b?a:b;
    long long min=a<b?a:b;
    int r=max%min;
    while(r){
        max = min;
        min = r;
        r= max%min;
    }
    return min;
}
void add(long long ans[],long long a1,long long a2,long long b1,long long b2)
{
    ans[0]= a1*b2+a2*b1;
    ans[1]= a2*b2;
    if(ans[0]==0){
        ans[1]=1;
        return;
    }
    long long tmp = factor(ans[0],ans[1]);
    ans[0]=ans[0]/tmp;
    ans[1]=ans[1]/tmp;      
    return ;
}
void print(long long a,long long b)
{
    if(b==0)
        return ;
    if(a==0){
        printf("0");
        return;
    }
    int flag = 0;
    if(a<0){
        flag = 1;
        a=-a;
    }
    long long tmp = factor(a,b),c;
    a=a/tmp;
    b=b/tmp;
    c=a/b;
    if(flag){
        if(b==1)
            printf("-%lld",c);
        else{
            if(c==0)
                printf("-%lld/%lld",a,b);
            else
                printf("-%lld %lld/%lld",c,a%b,b);
        }
    }
    else{
                if(b==1)
                        printf("%lld",c);
                else{
                        if(c==0)
                                printf("%lld/%lld",a,b);
                        else
                                printf("%lld %lld/%lld",c,a%b,b);
        }
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务