本题注意有一个坑:分子的计算结果可能为0,这个时候可能会出现浮点错误(反正我是出现了),避免除数为0情况出现.
#include <iostream>
typedef long long LL;
using namespace std;
/**
* 辗转相除法寻找最小公倍数
* @param a
* @param b
* @return
*/
LL find(LL a,LL b){
if(a<b){
LL tem=a;
a=b;
b=tem;
}
LL c,a1=a,b1=b;
do{
c=a%b;
a=b;
b=c;
}while (c!=0);
return (a1/a)*b1;
}
LL find1(LL a,LL b){
if(a<b){
LL tem=a;
a=b;
b=tem;
}
LL c,a1=a,b1=b;
do{
c=a%b;
a=b;
b=c;
}while (c!=0);
return a;
}
int main() {
int N;
cin>>N;
LL tops[N];
LL downs[N];
for (int i = 0; i < N; ++i) {
LL a,b;
scanf("%lld/%lld",&a,&b);
tops[i]=a;
downs[i]=b;
}
LL a=downs[0];
for (int j = 1; j < N; ++j) {
a=find(a,downs[j]);
}
LL sum=0;
for (int i = 0; i < N; ++i) {
tops[i]=tops[i]*(a/downs[i]);
sum+=tops[i];
}
if(sum==0){
cout<<0<<endl;
return 0;
}
if(sum/a==0){
LL val=find1(sum,a);
cout<<sum/val<<"/"<<a/val;
} else{
cout<<sum/a;
if (sum%a==0){
return 0;
}
sum=sum-(sum/a)*a;
LL val=find1(sum,a);
cout<<" "<<sum/val<<"/"<<a/val;
}
return 0;
}