算法


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.Scanner;

public class Main{
public static long gcb(long a, long b) { //求最大公约数

return b==0?a:gcb(b,a%b);
}
public static long getNum(long a, long b) { //求两个数的最小公倍数
return a * b/gcb(a,b);
}
public static long getNum_1(long[] num, int m) { //求多个数的最小公倍数
if(m == 1)
return num[m - 1];
return getNum(num[m - 1], getNum_1(num, m - 1));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int n = sc.nextInt();
String[] str = new String[n];
String[] str2 = new String[n];
long[] fz = new long[n];
long[] fm = new long[n];
for(int i = 0; i < n; i++) {

str[i] = sc.next();
str2 = str[i].split("/"); //以/来分割字符串
fz[i] = Long.parseLong(str2[0]);
fm[i] = Long.parseLong(str2[1]);
}
long gbs = getNum_1(fm, n);
long sum = 0;
for(int i = 0; i < n; i++) {
sum += gbs/fm[i]*fz[i];
}
if(sum == 0){
System.out.println(0);
}else if(Math.abs(sum) < gbs) {
if(gcb(sum, gbs) == 1)
System.out.println(sum + "/" + gbs);
else{
System.out.println(sum/gcb(sum,gbs) + "/" + gbs/gcb(sum,gbs));
}
}else if(sum == gbs) {
if(sum < 0)
System.out.println("-1");
else
System.out.println("1");
}else {
if(sum >= 0) {
long x = sum/gbs;
if(sum % gbs == 0)
System.out.println(x);
else{
long y = gcb((sum - gbs * x), gbs); //提取出整数后的分子和分母的最大公约数
System.out.println(x + " " + (sum - gbs * x) / y + "/" + gbs / y);
}
}else {
sum = -sum;
long x = sum/gbs;
if(sum % gbs == 0)
System.out.println(-x);
else{
long y = gcb((sum - gbs * x), gbs); //提取出整数后的分子和分母的最大公约数
System.out.println(-x + " " + (-(sum - gbs * x)) / y + "/" + gbs / y);
}
}
}
}
}
}