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;

}

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