PAT-A-1081 Rational Sum 【最大公约数】【最小公倍数】

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

最小公约数和最大公倍数问题 

具体做法是:用较大数除以较小数,再用出现的余数(第一余数)去除除数,再用出现的余数(第二余数)去除第一余数,如此反复,直到最后余数是0为止。如果是求两个数的最大公约数,那么最后的除数就是这两个数的最大公约数

       实质上是以下式子:

        

                     

最小公倍数就等于a*b/gcd(a,b);

 

 


#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
using namespace std;
long long getYue(long  a,long b){
	long temp;
    if(a < 0) a = -a;
    if(b < 0) b = -b;
    if(a<b){
        temp=a;
        a=b;
        b=temp;
    }
	while(b!=0) {    //通过循环求两数的余数,直到余数为0
    	   temp=a%b;
    	   a=b;    //变量数值交换
    	   b=temp;
    }
  	return a;
}

int main(){
	int n;
	scanf("%d",&n);
	long long  fenzi,fenmu,tfenzi,tfenmu,yue;
	scanf("%lld/%lld",&fenzi,&fenmu);
	for(int i=1;i<n;i++){
		scanf("%lld/%lld",&tfenzi,&tfenmu);
		fenzi=fenzi*tfenmu+tfenzi*fenmu;
		fenmu=fenmu*tfenmu;
        yue=getYue(fenzi,fenmu);
        fenzi=fenzi/yue;
        fenmu=fenmu/yue;
	}

    if(fenzi < 0){// 判断分子是否为负数
        printf("-");
        fenzi = -fenzi;
    }else if(fenzi == 0){// 如果分子为0,将分母置为1  
        fenmu=1;    
    }
    
    // 根据整数 真分数 假分数三种情况输出
    if(fenmu==1){    //fenmu等于有两种情况.1是分子为0,即结果为0,2是结果为整数,分子和分母约分导致分母为1
        printf("%lld\n", fenzi);
            
    }
    else if(fenzi < fenmu){
        printf("%lld/%lld\n", fenzi, fenmu);
    }else{
        printf("%lld %lld/%lld\n",fenzi / fenmu, fenzi % fenmu, fenmu);

    }
    return 0;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章