1081 Rational Sum(20 分)
2024-08-26 09:46:50
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 (≤), 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<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
struct Fraction{
ll up,dowm;
}; ll gcd(ll a,ll b){
return b == ? a : gcd(b,a%b);
} Fraction reduction(Fraction result){
if(result.dowm < ){
result.up = - result.up;
result.dowm = - result.dowm;
}
if(result.up == ){
result.dowm = ;
}else{
int d = gcd(abs(result.dowm),result.up);
result.dowm /= d;
result.up /= d;
}
return result;
} Fraction add(Fraction f1,Fraction f2){
Fraction result;
result.up = f1.dowm*f2.up + f2.dowm*f1.up;
result.dowm = f1.dowm*f2.dowm;
return reduction(result);
} void showResult(Fraction r){
reduction(r);
if(r.dowm == ) printf("%lld",r.up);
else if(abs(r.up) > abs(r.dowm)){
printf("%lld %lld/%lld",r.up/r.dowm,r.up%r.dowm,r.dowm);
}else{
printf("%lld/%lld",r.up,r.dowm);
}
} int main(){
int n;
scanf("%d",&n);
Fraction sum,temp;
sum.up = , sum.dowm = ;
for(int i = ; i < n; i++){
scanf("%lld/%lld",&temp.up,&temp.dowm);
sum = add(sum,temp);
}
showResult(sum);
return ;
}
最新文章
- Javascript、Jquery获取浏览器和屏幕各种高度宽度
- [LeetCode] Remove Linked List Elements
- ssh升级
- sobel算子原理及opencv源码实现
- Windows Live Writer技巧
- 第四章 跨平台图像显示库——SDL 第一节 与SDL第一次亲密接触
- OkHttpUtils
- mybatis-generator-core自动生成do、mapping、dao 代码
- 数据结构——HDU1312:Red and Black(DFS)
- linux下ssh使用和配置
- strut1.X和spring整合的二种方法
- 3D Touch开发
- 201521123039 《java程序设计》第九周学习总结
- 在MAC OS X中默认的Web共享目录
- Scala集合Map
- [UE4]Event Tick
- IDEA文件对比
- docker入门 什么是docker? 为什么使用docker?
- C# 分支语句 练习题(中间变量,随机数)
- [csp-201509-3]模板生成系统
热门文章
- 国画经典之梅花PSD素材
- linkedhashSet和hashSet和TreeSet的区别(转)
- <;%!%>;声明的变量和在<;%%>;中声明的变量的区别
- 剑指offer12 打印从1到N位的所有数字,处理大整数情况
- CodeForces - 613D:Kingdom and its Cities(虚树+DP)
- MySQL11月16-11月21日活动赠送的优惠券使用率_20161124
- 搭建基于Nagios的监控系统——之监控远程Linux服务器
- bzoj4176
- Windows窗体间的数据交互
- 虚拟机中的Linux安装VMware&;nbsp;Tools