1081. Rational Sum (20)

来源:互联网 发布:java生产者和消费者 编辑:程序博客网 时间:2024/05/17 02:49

1081. Rational Sum (20)

 

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

最后一个测试点和为0,注意。

#include <stdio.h>void sim(long long  a[]){long long a1,b1,i;a1 = a[0];b1 = a[1];for(i=2;i<a1;i++){if(a1%i == 0 && b1 %i ==0){a1 = a1/i;b1 = b1/i;i = 2;}}a[0] = a1;a[1] = b1;}void add(long long a[],long long b[]){long long temp=a[1];a[1] = a[1] * b[1];a[0] = a[0] * b[1] + b[0] * temp;}int main(){long long a[2]={0,1},b[2];long long N,i;scanf("%lld",&N);for(i=0;i<N;i++){scanf("%lld/%lld",&b[0],&b[1]);sim(b);add(a,b);sim(a);}if(a[0] < 0){a[0] = -a[0];putchar('-');}if( a[0]/a[1] != 0){printf("%lld",a[0]/a[1]);if(a[0]%a[1]!=0)putchar(' ');}else{if(a[0]%a[1] == 0){puts("0");}}if(a[0]%a[1] != 0){printf("%lld/%lld",a[0]%a[1],a[1]);}return 0;}


 

 

 

 

0 0