PAT 1081 Rational Sum [分数的四则运算] [最大公约数和最小公倍数]

本文介绍了一种计算多个有理数之和的算法,通过最大公约数和最小公倍数的计算实现分数的加法。文章提供了完整的C语言代码实现,并讨论了数据范围和特殊情况的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

-----------------------------------这是题目和解题的分割线-----------------------------------

对最大公约数和最小公倍数的考察。

注意,数据范围in the range of long int,当两个数据相乘的时候,最大可以达到long long。

给出几组容易错的数据

2   -4/3 8/6    // 0

2   1/3 -1/2    // -1/6

2   13/6 -7/6  // 1

不过这道题的数据十分非常相当弱,一些特例不通过也不会报错。

#include<stdio.h>
#include<stdlib.h>

struct node
{
	long long x,y;
}num[105],tmp,sum;

//最大公约数 
long long findGCD(long long a,long long b)
{
	if(b==0) return a;
	return findGCD(b,a%b);
}

node sumFx(node a,node b)
{
	long long maxG,minG,x,newx,newy;
	maxG = findGCD(a.y,b.y);
	//最小公倍数 = a*b/最大公约数 新的分母 
	minG = (a.y)*(b.y)/maxG;
	//新的分子 
	x = minG/a.y*a.x+minG/b.y*b.x;
	//约分(abs保证最大公约数为正数) 
	tmp.x = x/findGCD(abs(x),minG);
	tmp.y = minG/findGCD(abs(x),minG);
	return tmp;
}

int main()
{
	int i,n;
	long long x,y,minG,maxG;
	scanf("%d",&n);
	if(n==0) {printf("0");return 0;}
	scanf("%lld/%lld",&sum.x,&sum.y);
	for(i=1;i<n;i++)
	{
		scanf("%lld/%lld",&num[i].x,&num[i].y);
		if(num[i].x==0) continue;
		sum = sumFx(num[i],sum); //两两相加			
	}		
	//printf("%lld/%lld\n",sum.x,sum.y);
	if(!sum.x) {printf("0");return 0;}
	//如果分母大于等于分子,需比较绝对值 
	if(abs(sum.x)>=abs(sum.y))
	{
		printf("%lld",sum.x/sum.y);
		long long t = sum.x-sum.x/sum.y*sum.y;
		if(t) printf(" %lld/%lld",t,sum.y);
	} 	
	else printf("%lld/%lld",sum.x,sum.y);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值