a/b + c/d
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 9099 Accepted Submission(s): 5165
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
Source
Recommend
农夫山泉的说.没有第一时间反应过来,遗憾!
首先int x=a*d+b*c,
然后int y=b*d;
然后求 x和y的最大公约数;
x和y再都除以最大公约数就行了.
import java.io.*;
import java.util.*;
public class Main
{
public static int gcd(int m, int n)
{
int temp = 0;
if (m < n)
{
temp = m;
m = n;
n = temp;
}
while (n > 0)
{
temp = m % n;
m = n;
n = temp;
}
return m;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int t, a, b, c, d;
t = input.nextInt();
for (int i = 0; i < t; i++)
{
int e, f;
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
d = input.nextInt();
int x = a * d + b * c;
int y = b * d;
e = x / gcd(x, y);
f = y / gcd(x, y);
System.out.println(e + " " + f);
}
}
}