a/b + c/d
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 10124 Accepted Submission(s): 5669
Problem Description
给你2个分数,求他们的和,并要求和为最简形式。
Input
输入首先包含一个正整数T(T<=1000),表示有T组测试数据,然后是T行数据,每行包含四个正整数a,b,c,d(0<a,b,c,d<1000),表示两个分数a/b 和 c/d。
Output
对于每组测试数据,输出两个整数e和f,表示a/b + c/d的最简化结果是e/f,每组输出占一行。
Sample Input
2 1 2 1 3 4 3 2 3
Sample Output
5 6 2 1#include <iostream> #include <string> using namespace std; int com1(int x,int y)//最小公倍数 { int r=1; int xx;int yy; xx=x;yy=y; while(r!=0) { r=x%y; x=y; y=r; } return (xx*yy)/x; } int com2(int x,int y)//最大公约数 { int r=1; int xx;int yy; xx=x;yy=y; while(r!=0) { r=x%y; x=y; y=r; } return x; } int main() { int T,a,b,c,d,e,f,q; cin>>T; while(T--) { cin>>a>>b>>c>>d; if(b==d) { e=a+c; f=b; if(com2(e,f)==1) cout<<e<<" "<<f<<endl; else cout<<e/com2(e,f)<<" "<<f/com2(e,f)<<endl; } if(b!=d) { q=com1(b,d); e=q/b*a+q/d*c; f=q; if(com2(e,f)==1) cout<<e<<" "<<f<<endl; else cout<<e/com2(e,f)<<" "<<f/com2(e,f)<<endl; } } return 0; }