1081. Rational Sum (20)

简介: 1081. Rational Sum (20)

20201230173427514.png

算法思想:

①numerator接收分子,denominator接收分母;每次根据分母求最小公倍数l,然后分母通分累加到sum上。遍历结束后sum是分母,l是分子。

②碾转相处法求最大公约数,分子分母一起除公约数(绝对值),然后分子分母约分输出。

#include<iostream>
using namespace std;
long long gcd(long long a, long long b)
{
  return b == 0 ? a : gcd(b, a % b);//gcd(a,b) = gcd(b,a % b)   0的最大公约数就是另一个数
}
long long lcm(long long a, long long b) {//两个数的乘积等于这两个数的最大公约数与最小公倍数的积。即(a,b)×[a,b]=a×b
  if (a == 0 || b == 0) {
    return 0;
  }
  return a * b / gcd(a, b);
}
int main(){
    int n;
    cin>>n;
    long long numerator;//接收分子
    long long denominator;//接收分母
    long long l=1;//最小公倍数
    long long m=1;//倍数
    char c;//接收‘/’除号
    long long sum=0;
    for(int i=0;i<n;i++){
        cin>>numerator>>c>>denominator;
        long long last=l;
        l=lcm(l,denominator);
        c=l/denominator;
        sum*=(l/last);
        sum+=c*numerator;
    }
    long long res1=sum/abs(gcd(sum,l));
    long long res2=l/abs(gcd(sum,l));
    if(res1/res2){
        cout<<res1/res2;
        if(res1-(res1/res2)*res2)
            cout<<" "<<res1-(res1/res2)*res2<<"/"<<res2;
        cout<<endl;
    }else if(res1==0){
        cout<<0<<endl;
    }
    else{
        cout<<res1<<'/'<<res2<<endl;
    }
}
相关文章
|
11月前
|
C++
【PAT甲级 - C++题解】1081 Rational Sum
【PAT甲级 - C++题解】1081 Rational Sum
69 0
|
SQL
sum函数
sum函数
86 0
ICPC North Central NA Contest 2018 C . Rational Ratio(结论 模拟 gcd)
ICPC North Central NA Contest 2018 C . Rational Ratio(结论 模拟 gcd)
89 0
【1081】Rational Sum (20 分)
【1081】Rational Sum (20 分) 【1081】Rational Sum (20 分)
73 0
【1088】Rational Arithmetic (20 分)
【1088】Rational Arithmetic (20 分) 【1088】Rational Arithmetic (20 分)
83 0
【1059】Prime Factors (25 分)
【1059】Prime Factors (25 分) 【1059】Prime Factors (25 分)
86 0
1081. Rational Sum (20)
#include using namespace std; long gcd(long a, long b){ while (a) { long t = a; a = b % ...
673 0
1088. Rational Arithmetic (20)
For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.
775 0
1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
768 0