1081. Rational Sum (20)
来源:互联网 发布:java生产者和消费者 编辑:程序博客网 时间:2024/05/17 02:49
1081. Rational Sum (20)
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/3Sample Output 1:
3 1/3Sample Input 2:
24/3 2/3Sample Output 2:
2Sample Input 3:
31/3 -1/6 1/8Sample 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;}
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 欢迎使用CSDN-markdown编辑器
- Hadoop--06--MapReduce编程基础
- 【BZOJ2049】[Sdoi2008]Cave洞穴勘测
- 经典编程问题之:选择排序、冒泡排序、汉诺塔游戏,均用js代码实现
- 加载本地图片oom处理
- 1081. Rational Sum (20)
- C语言nice()函数:改变进程优先顺序
- Codeforces 698A Vacations
- 使用easyui时导入的jar包
- TFS 2015 敏捷开发实践 - 在Kanban上运行一个Sprint
- C++中的explicit关键字
- Android的onCreateOptionsMenu()创建菜单Menu详解
- android群英传学习笔记-自定义TopBar
- Java的异常处理