题目:
Description
输入两个分数a/b和c/d,计算a/b+c/d.
Input
第一行是一个整数T (T<=10),表示总共有T组数据.
接下来的T行,每行是一组数据,包括4个正整数a, b, c, d (1<=a, b, c, d<=10000).
Output
对于每组数据,输出a/b和c/d的和. 注意要将和化成最简分数,和的分子可以大于分母. 如果分母为1,只需输出分子.
Sample Input
3 1 1 1 2 1 6 1 3 4 5 1 5
Sample Output
3/2 1/2 1
要点。。。
求最大公约数的方法,然后就可以化简了。然后就是判断分母等于分子,或是可以被整除的情况。
while (n != 0) {
int temp = m % n;
m = n;
n = temp;
}
return m;
解法:
// Copyright <lijiancheng> [2014]
// Sicily 4629
#include <iostream>
using namespace std;
void simplify(int e, int d) {
if (e == d) {
cout << "1" << endl;
return;
}
if (e % d == 0 && (e > d)) {
cout << e/d << endl;
return;
}
int m = e;
int n = d;
while (n != 0) {
int temp = m % n;
m = n;
n = temp;
}
cout << e/m << "/" << d/m << endl;
}
int main() {
int t;
int a, b, c, d;
cin >> t;
while (t--) {
cin >> a >> b >> c >> d;
int denominator = b * d;
int element = (a * d) + (c * b);
simplify(element, denominator);
}
return 0;
}