题目描述:原题链接
Everybody knows the typical A+B problem, this one is much harder, instead of A+B it’s going to be A+B+C, but with fractions.
Input
An integer T (1<=T<=103), the number of test cases T lines follow, each with 3 fraction numbers, each in the form nd (1<=n,d<=106)
Output
One line per test case, a single simplified fraction in the format numden
Example
input
2
1/2 1/3 1/4
3/2 1/2 2/2
output
13/12
3/1
思路:
用gcd()正常算,注意数据范围。
1.我自己的做法
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int N=200010;
ll gcd(ll a,ll b)
{
if(b==0) return a;
return gcd(b,a%b);
}
int main ()
{
int T;
scanf("%d",&T);
while(T--)
{
ll a,b,c,x,y,z;
scanf("%lld/%lld %lld/%lld %lld/%lld",&a,&x,&b,&y,&c,&z);
ll num1=x*y/gcd(x,y);
num1=num1*z/gcd(num1,z);
ll num2=(num1/x)*a+(num1/y)*b+(num1/z)*c; //这步要注意先除再乘不然会爆long long
ll key=gcd(num1,num2);
printf("%lld/%lld\n",num2/key,num1/key);
}
return 0;
}
2.简化的方法
ll num1=x*y*z;
ll num2=a*y*z+b*x*z+c*x*y;
while(1)
{
ll k=gcd(num1,num2);
if(k==1) break;
num1/=k;
num2/=k;
}