题目来源:PAT (Advanced Level) Practice
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/3
Sample Output 1:
3 1/3
Sample Input 2:
2
4/3 2/3
Sample Output 2:
2
Sample Input 3:
3
1/3 -1/6 1/8
Sample Output 3:
7/24
words:
Rational 合理的,有理数 numerator 分子 denominator 分母 factor 因子,因素
fractional 分数的
思路:
1. 本题的意思是求n个分数的和,每个输入的分数由分子和分母构成;而最终的计算结果由整数部分、分子和分母构成,若整数部分为0,则只输出分数部分,若分子为0,则只输出整数部分;
2. 首先用a和b表示输入的分数的分子和分母,用ans_a、ans_b、ans_b表示求和结果分数的分子、分母和整数部分;其中初始时ans_a=1,ans_b=1,ans_c=0;
3. 每输入一个分数,即a和b,都使其与ans_a、ans_b做分数加法运算,即ans_a=ans_a*b+ans_b*a,ans_b*=b ,在相加过程中不计算ans_c,直到所有分数的求和结束后再求ans_c,而且每次相加后都要约分;
4. 求和结束和,求和结果先减1(由于求和结果初始为1),即ans_a-=ans_b,然后求整数部分,即ans_c=ans_a/ans_b,最后简化分子,即ans_a%=ans_b;
//PAT ad 1081 Rational Sum
#include <iostream>
using namespace std;
void yufen(long long &a,long long &b) //给a和b约分
{
int flag1=1,flag2=1;
if(a<0)
{
flag1=-1;
a=-a;
}
if(b<0)
{
flag2=-1;
b=-b;
}
for(int i=2;i<=a&&i<=b;i++)
while(a%i==0&&b%i==0)
{
a/=i;
b/=i;
}
a*=flag1;b*=flag2;
}
void And(int a,int b,long long &ans_a,long long &ans_b) //两分数求和
{
ans_a=ans_a*b+ans_b*a; //分子
ans_b*=b; //分母,通分,
yufen(ans_a,ans_b); //约分
}
int main()
{
int n,i;
scanf("%d",&n);
int a,b;
long long ans_a=1,ans_b=1,ans_c=0;
for(i=0;i<n;i++) //循环输入并求和
{
scanf("%d/%d",&a,&b);
And(a,b,ans_a,ans_b);
}
ans_a-=ans_b; //分数减一
ans_c=ans_a/ans_b; //整数部分
ans_a%=ans_b; //分子部分
//输出
if(ans_a==0) //分子为0
printf("%d\n",ans_c);
else if(ans_c==0) //整数部分为0
printf("%d/%d\n",ans_a,ans_b);
else
printf("%d %d/%d\n",ans_c,ans_a,ans_b);
return 0;
}