夏虫
package com.test;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main main = new Main();
Scanner sc = new Scanner(System.in);
System.out.print("请输入测试组数:");
int t = sc.nextInt();
System.out.print("请输入" + t + "个真分数(如3/7):\n");
String[] strs = new String[t];
String[] results = new String[t];
for (int i = 0; i
System.out.print("第" + (i + 1) + "个分数:");
strs[i] = sc.next();
results[i] = main.getResult(strs[i]);
while (results[i] == null) {
System.out.print("输入错误,请重新输入第" + (i + 1) + "个分数:");
strs[i] = sc.next();
results[i] = main.getResult(strs[i]);
}
}
for (int i = 0; i
System.out.println(strs[i] + "=" + results[i]);
}
}
public String getResult(String str) {
String result = "";
String[] strs = str.split("/");
if (strs.length != 2) {
return null;
}
long a, b;
try {
a = Integer.valueOf(strs[0]);
b = Integer.valueOf(strs[1]);
if (a >= b || a <= 0 || b <= 0) {
return null;
}
long[] I = simple(a, b);
if (a != I[0]) {
a = I[0];
b = I[1];
result = a + "/" + b + "=";
}
while (a != 1) {
long temp = b / a + 1;
result = result + "1/" + temp + "+";
a = a * temp - b;
b = b * temp;
I = simple(a, b);
a = I[0];
b = I[1];
}
if (a == 1) {
result = result + "1/" + b;
}
} catch (Exception e) {
return null;
}
return result;
}
public long[] simple(long a, long b) {
for (long i = a; i > 1; i--) {
if (b % i == 0 && a % i == 0) {
a = a / i;
b = b / i;
simple(a, b);
}
}
return new long[]{a, b};
}
}