https://pintia.cn/problem-sets/994805046380707840/problems/994805133597065216
本题不难… gcd + lcm 就搞定。
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StreamTokenizer st = new StreamTokenizer(br);
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] A = sc.next().split("/");
int a = Integer.parseInt(A[0]); // 分子
int b = Integer.parseInt(A[1]); // 分母
int t = gcd(a, b);
if(t != 0) {
a /= t;
b /= t;
}
n--;
while(n-- != 0) {
A = sc.next().split("/");
int aa = Integer.parseInt(A[0]);
int bb = Integer.parseInt(A[1]);
int lcm = lcm(b, bb); // 作用:通分时要求最小公倍数
a = a * lcm / b + aa * lcm / bb;
b = lcm;
int gcd = gcd(a, b);
if(gcd != 0) { // 化简
a /= gcd;
b /= gcd;
}
}
if(a != 0 && b != 0 && Math.abs(a) < Math.abs(b)) out.printf("%d/%d", a % b, b); // 真分数
else if(a % b == 0) out.printf("%d", a / b); // 整数
else out.printf("%d %d/%d", a / b, a % b, b); // 假分数 => 带分数
out.flush();
}
public static int lcm(int a, int b) {
return a * b / gcd(a, b);
}
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static int nextInt() throws Exception {
st.nextToken();
return (int) st.nval;
}
public static String nextStr() throws Exception {
st.nextToken();
return st.sval;
}
}