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/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
#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;}
- 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)
- JVM加载对象时内存加载顺序
- 数据结构/实现二叉树的前序/中序/后序非递归遍历
- 收藏版:java常见面试题目精讲视频教程
- base64编码的图片在HTML的img控件中显示
- java多线程基础知识
- 1081. Rational Sum (20)
- ElasticSearch之排序使用-ES常用排序方法
- G
- POJ2393 Yogurt factory (贪心 | dp)
- 第九章:用户自己建立数据类型(结构体)
- 记一次,编译MuseScore的经历
- 使用OpenFiler来模拟存储配置RAC中ASM共享盘及多路径(multipath)的测试
- POJ1067--取石子游戏(威佐夫博弈)
- 笔记:回调的实现