从分母为2分子为1的分数开始,逐个相加,每次都做通分,保证分母一致,整个过程中只做乘法运算,算法应该是没有问题的,但用例有几个没法过:
1、输入:8/11
输出:1/2+1/5+1/37+1/4070
2、输入:2/4
输出:1/2
3、输入:43/77
2、输入:2/4
输出:1/2
3、输入:43/77
输出:1/2+1/18+1/347+1/3997+1/3999+1/4000+1/4001+1/4008+1/4009+1/4010+1/4011+1/4014+1/4018+1/4019+1/4020+1/4023+1/4025+1/4028+1/4029+1/4032+1/4036+1/4037+1/4043+1/4044+1/4045+1/4047+1/4051+1/4053+1/4056+1/4057+1/4061+1/4063+1/4069+1/4071+1/4072+1/4075+1/4076+1/4080
16/19 组用例通过
运行时间40ms
占用内存10996KB
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String s = in.nextLine();
String[] s1 = s.split("/");
int fz = Integer.valueOf(s1[0]);
int fm = Integer.valueOf(s1[1]);
int sum = 0;
int i = 2;
StringBuffer sb = new StringBuffer();
while (sum != fz) {
int tempM = i * fm;
int tempZ = fz * i;
int tempS = sum * i;
if (tempS + fm <= tempZ) {
sum = tempS + fm;
fm = tempM;
fz = tempZ;
sb.append("1/").append(i).append("+");
}
i++;
}
System.out.println(sb.substring(0, sb.length() - 1));
}
}
}

京公网安备 11010502036488号