PAT_A1081 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<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node{
ll a, b;
};
int gcd(int a, int b){
return b ? gcd(b, a%b):a;
}
node myadd(node a, node b){
ll q = a.a*b.b + b.a*a.b;
ll w = a.b * b.b;
ll d = gcd(q, w);
d = d<0 ? -d : d;
a.a = q/d;
a.b = w/d;
return a;
}
node r, t;
int main(){
r.a=0; r.b=1;
ll n; scanf("%lld", &n);
for(ll i = 0; i < n; i++){
ll a,b,d;
scanf("%lld/%lld", &a, &b);
d = gcd(a, b);
d = d<0 ? -d : d;
t.a = a/d;
t.b = b/d;
r = myadd(r, t);
}
if(abs(r.a) >= r.b)
r.a%r.b==0 ? printf("%lld", r.a/r.b) : printf("%lld %lld/%lld", r.a/r.b, r.a%r.b, r.b);
else
r.a == 0 ? printf("0") : printf("%lld/%lld", r.a, r.b);
return 0;
}
总结
1、 #分数 本题主要考察分数的运算,和分数的输出
2、数据范围为int,但两分母相乘时,最大可达到long long,应该用long long
3、测试点4会检查0的输出
4、[[分数及其运算模板]]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人