1081. Rational Sum (20)
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/3Sample Output 1:
3 1/3Sample Input 2:
2 4/3 2/3Sample Output 2:
2
#include<iostream> #include<vector> #include<string> using namespace std; typedef long long ll; ll getGCD(ll a,ll b){ ll temp; if(a < b){ temp = a; a = b; b = temp; } if(a%b == 0){ return b; }else{ return getGCD(b,a%b); } } ll doLCM(vector<ll> array,ll size){ ll x,y,num=array[0],i,gcd; for(i=0;(i+1)<size;i++){ x=num; y=array[i+1]; gcd = getGCD(x,y); num = x/gcd * y/gcd * gcd; } return num; } int main() { ll n; cin>>n; vector<ll> va,vb; vector<char> vc; for(ll i=0;i<n;i++){ ll a=0,b=0; char c; cin>>a>>c>>b; va.push_back(a); vb.push_back(b); vc.push_back(c); } ll tt=0; tt=doLCM(vb,vb.size()); ll ans=0; for(ll i=0;i<va.size();i++){ ans+=(va[i]*(tt/vb[i])); } if(ans==0){ cout<<0<<endl; }else{ ll k=0; k=getGCD(ans,tt); tt/=k; ans/=k; ll integer=ans/tt; ans-=(tt*integer); if(integer==0){ if(ans!=0) cout<<ans<<'/'<<tt<<endl; else{ cout<<0<<endl; } }else{ if(ans!=0) cout<<integer<<' '<<ans<<'/'<<tt<<endl; else{ cout<<integer<<endl; } } } return 0; }