本题的要求很简单,就是求N个数字的和。麻烦的是,这些数字是以有理数“分子/分母”的形式给出的,你输出的和也必须是有理数的形式。
输入格式:
输入第一行给出一个正整数N(<=100)。随后一行按格式“a1/b1 a2/b2 ...”给出N个有理数。题目保证所有分子和分母都在长整型范围内。另外,负数的符号一定出现在分子前面。
输出格式:
输出上述数字和的最简形式 —— 即将结果写成“整数部分 分数部分”,其中分数部分写成“分子/分母”,要求分子小于分母,且它们没有公因子。如果结果的整数部分为0,则只输出分数部分。
输入样例1:
5
2/5 4/15 1/30 -2/60 8/3
输出样例1:
3 1/3
输入样例2:
2
4/3 2/3
输出样例2:
2
输入样例3:
3
1/3 -1/6 1/8
输出样例3:
输入格式:
输入第一行给出一个正整数N(<=100)。随后一行按格式“a1/b1 a2/b2 ...”给出N个有理数。题目保证所有分子和分母都在长整型范围内。另外,负数的符号一定出现在分子前面。
输出格式:
输出上述数字和的最简形式 —— 即将结果写成“整数部分 分数部分”,其中分数部分写成“分子/分母”,要求分子小于分母,且它们没有公因子。如果结果的整数部分为0,则只输出分数部分。
输入样例1:
5
2/5 4/15 1/30 -2/60 8/3
输出样例1:
3 1/3
输入样例2:
2
4/3 2/3
输出样例2:
2
输入样例3:
3
1/3 -1/6 1/8
输出样例3:
7/24
不是很会,希望指教。。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String num[] = new String[n];
int sum = 0;
int A = 0, B = 1;
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
for (String i : num) {
i = sc.next();
if (i.contains("/")) {
int a = Integer.parseInt(i.substring(0, i.indexOf("/")));
int b = Integer.parseInt(i.substring(i.indexOf("/") + 1, i.length()));
list1.add(a);
list2.add(b);
} else {
sum += Integer.parseInt(i);
}
}
for (int j = 0; j < list2.size(); j++) {
B *= (int) list2.get(j);
}
for (int i = 0; i < list1.size(); i++) {
A += (int) list1.get(i) * (B / (int) list2.get(i));
}
int a = (A + sum * B) / B;
int b = (A + sum * B - B * a) ;
if(b>0){
int y=1;
int i=2;
String s1="";
int c=b;
while(i<=c){
if(c%i==0){
s1+=i+" ";
c/=i;
}else {
i++;
}
}
int j=2;
String s2="";
int d=B;
while(j<=d){
if(d%j==0){
s2+=j+" ";
d/=j;
}else {
j++;
}
}
String ss1[]=s1.split(" ");
String ss2[]=s2.split(" ");
out:for(String sss1:ss1){
for(String sss2:ss2){
if(sss1.equals(sss2)){
y*=Integer.parseInt(sss1);
continue out;
}else {
y*=1;
}
}
}
int b1=0;
int B1=0;
if(y!=0){
b1=b/y;
B1=B/y;
}else{
b1=b;
B1=B;
}
if(a == 0 && b1==0){
System.out.println("0");
} else if (a == 0 && b1!=0 ) {
System.out.println( b1+"/"+B1);
} else if(a != 0 && b1!=0){
System.out.println(a + " " + b1+"/"+B1);
} else if(b1==0) {
System.out.println( a );
}
}else {
int y=1;
int i=2;
String s1="";
int c=-b;
while(i<=c){
if(c%i==0){
s1+=i+" ";
c/=i;
}else {
i++;
}
}
int j=2;
String s2="";
int d=B;
while(j<=d){
if(d%j==0){
s2+=j+" ";
d/=j;
}else {
j++;
}
}
String ss1[]=s1.split(" ");
String ss2[]=s2.split(" ");
out:for(String sss1:ss1){
for(String sss2:ss2){
if(sss1.equals(sss2)){
y*=Integer.parseInt(sss1);
continue out;
}else {
y*=1;
}
}
}
int b1=0;
int B1=0;
if(y!=0){
b1=b/y;
B1=B/y;
}else{
b1=b;
B1=B;
}
if(a == 0 && b1==0){
System.out.println("0");
} else if (a == 0 && b1!=0 ) {
System.out.println( "-"+b1+"/"+B1);
} else if(a != 0 && b1!=0){
System.out.println(a + "-" + b1+"/"+B1);
} else if(b1==0) {
System.out.println(a);
}
}
}
}