-
总时间限制:
- 1000ms 内存限制:
- 65536kB
-
描述
-
输入n个分数并对他们求和,并用最简形式表示。所谓最简形式是指:分子分母的最大公约数为1;若最终结果的分母为1,则直接用整数表示。
如:5/6、10/3均是最简形式,而3/6需要化简为1/2, 3/1需要化简为3。
分子和分母均不为0,也不为负数。
输入
-
第一行是一个整数n,表示分数个数,1 <= n <= 10;
接下来n行,每行一个分数,用"p/q"的形式表示,不含空格,p,q均不超过10。
输出
- 输出只有一行,即最终结果的最简形式。若为分数,用"p/q"的形式表示。 样例输入
-
2 1/2 1/3
样例输出
-
5/6
- 题解:
- 我先把第一个分数作为初值,然后不断和下一个分数先通分,后相加。
例如1/2和1/3先通分为3/6和2/6,然后分子相加得5/6。
- 最后再约分,方法是分子分母同时除以gcd(分子,分母)
- 代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
#include<stack>
#include<queue>
#define MAXA 10000
typedef long long LL;
using namespace std;
int n,son,mother,s,m;
char ch;
int gcd(int a,int b) {
if(b == 0)
return a;
return gcd(b,a%b);
}
int main() {
scanf("%d",&n);
scanf("%d %c %d",&son,&ch,&mother);
s = son;m = mother;
for(int i=1;i<=n-1;i++) {
scanf("%d %c %d",&son,&ch,&mother);
int temp_m = m,temp_mother = mother;
m *= temp_mother; s *= temp_mother;
mother *= temp_m; son *= temp_m;
s += son;
}
if(gcd(s,m) == 1) {
if(m != 1) {
printf("%d/%d",s,m);
return 0;
}
else {
printf("%d",s);
return 0;
}
}
else {
int simplify = gcd(s,m);
s /= simplify;
m /= simplify;
if(m == 1) {
printf("%d",s);
return 0;
}
printf("%d/%d",s,m);
return 0;
}
}