PTA_L1-009 N number of summing (20 minutes)

Summing the number L1-009 N

The requirements of this problem is very simple, is to compute the numbers N and. The trouble is, these numbers are rational molecular / denominator form gives you the output and must also be in the form of rational numbers.

Input format:
input of the first row is given a positive integer N (≤100). Then the format line a1 / b1 a2 / b2 ... N given rational number. Topic to ensure that all the numerator and denominator are within range of a long integer. Further, negative symbol must appear in front of the molecule.

Output format:
its simplest form the digital output and the - write result integer part soon fractional portion with the fractional portion written numerator / denominator, the denominator is less than the required molecules and they have no common factors. If the integer portion of the result is 0, only the output of the fractional part.

Sample Input 1:
5
2/5 8/3 4/15 1/30 -2/60
Output Sample 1:
3 1/3
Input Sample 2:
2
4/3 2/3
Output Sample 2:
2
input sample 3:
3
1/3 -1/6 1/8
output sample 3:
7/24

Thinking:
definition of two arrays, a molecular memory, b keep the denominator. Find the maximum common multiple of the denominator. Then Molecular common denominator. Molecular then stored into sum2 sum1 denominator, and then about minutes, then sum1 / sum2 an integer part, the integer part if not outputs 0, 0 is the fractional part between the outputs. Finally, determine whether the negative. If negative output "-." (SUM1 and sum2 be defined as type long long)
complete code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[105];
ll b[105];
ll gcd(ll a,ll b)                   //最大公约数
{
    return b==0?a:gcd(b,a%b);
}
ll gbd(ll a,ll b)
{
    return a/gcd(a,b)*b;        //防溢出,求最小公倍数
}
int main()
{
    int n;
    cin>>n;
    ll num1=0;
    ll num2=0;
    for(int i=0;i<n;i++)
    {
        scanf("%lld/%lld",&a[i],&b[i]);
    }
    num2=b[0];
    for(int i=1;i<n;i++)        //分母
    {
        num2=gbd(num2,b[i]);
    }
    for(int i=0;i<n;i++)        //分子
    {
        num1+=num2/b[i]*a[i];
    }
    ll x=num1/num2;         //整数
    ll y=abs(num1%num2);   //余数
    if(y==0)                //为整数没有分数部分
    {
        cout<<x<<endl;
    }
    else
    {
        if(x!=0)
        {
            cout<<x<<" ";
        }
        if(num1<0)      //负数
        {
            cout<<"-";
        }
        cout<<y/gcd(num2,y)<<"/"<<gbd(num2,y)/y<<endl;
    }
    return 0;
}


Link to the original question:
https://pintia.cn/problem-sets/994805046380707840/problems/994805133597065216

Published 87 original articles · 98 won praise · views 4942

Guess you like

Origin blog.csdn.net/qq_45856289/article/details/104932335