简化Java中的分数

我的任务是发展理性课程。 如果500和1000是我的输入,则(½)必须是我的输出。 我自己写了一个程序来找到它。

还有另一种找到解决方案的最佳方法,或者我的程序已经是最好的了吗?

public class Rational { public static void main(String[] args){ int n1 = Integer.parseInt(args[0]); int n2 = Integer.parseInt(args[1]); int temp1 = n1; int temp2 = n2; while (n1 != n2){ if(n1 > n2) n1 = n1 - n2; else n2 = n2 - n1; } int n3 = temp1 / n1 ; int n4 = temp2 / n1 ; System.out.print("\n Output :\n"); System.out.print(n3 + "/" + n4 + "\n\n" ); System.exit(0); } } 

有趣的问题。 这里有一些可执行代码,只需几行即可完成:

 /** @return the greatest common denominator */ public static long gcm(long a, long b) { return b == 0 ? a : gcm(b, a % b); // Not bad for one line of code :) } public static String asFraction(long a, long b) { long gcm = gcm(a, b); return (a / gcm) + "/" + (b / gcm); } public static void main(String[] args) { System.out.println(asFraction(500, 1000)); // "1/2" System.out.println(asFraction(17, 3)); // "17/3" System.out.println(asFraction(462, 1071)); // "22/51" } 

你需要GCD。 既可以像Nathan一样使用BigInteger,也可以使用自己的BigInteger。

 public int GCD(int a, int b){ if (b==0) return a; return GCD(b,a%b); } 

然后你可以用GCD划分每个数字,就像你上面所做的那样。

这将给你一个不正确的分数。 如果您需要混合分数,那么您可以获得新数字。 例如,如果您有1500和500的输入,那么最终将以3/2作为答案。 也许你想要1 1/2。 所以你只需要除以3/2得到1,然后得到3/2的余数也是1.分母将保持不变。

 whole = x/y; numerator x%y; denominator = y; 

万一你不相信我这样做,你可以查看http://en.wikipedia.org/wiki/Euclidean_algorithm

我碰巧喜欢递归函数,因为它干净简单。

您的算法很接近,但不完全正确。 此外,如果要查找gcd,您应该创建一个新函数。 只是让它更清洁,更容易阅读。 您也可以测试该function。

作为参考,您实现的是原始的减法 欧几里德算法来计算两个数的最大公约数 。

更快的版本是使用整数除法的余数,例如%而不是-在你的循环中:

 while (n1 != 0 && n2 != 0){ if(n1 > n2) n1 = n1 % n2; else n2 = n2 % n1; } 

…然后确保你将使用非零的那个。

一个更精简的版本是这样的:

 while(n1 != 0) { int old_n1 = n1; n1 = n2 % n1; n2 = old_n1; } 

然后使用n1。 Matt的答案显示了相同算法的递归版本。

你应该使这个类不是静态方法的容器。 这是一个骨架

 import java.math.BigInteger; public class BigRational { private BigInteger num; private BigInteger denom; public BigRational(BigInteger _num, BigInteger _denom) { //put the negative on top // reduce BigRational using the BigInteger gcd method } public BigRational() { this(BigInteger.ZERO, BigInteger.ONE); } public BigRational add(BigRational that) { // return this + that; } . . . //etc } } 

我有一个类似我使用的BigRational类。 GcdFunction使用了BigIntegergcd函数:

 public class GcdFunction implements BinaryFunction { @Override public BigRational apply(final BigRational left, final BigRational right) { if (!(left.isInteger() && right.isInteger())) { throw new EvaluationException("GCD can only be applied to integers"); } return new BigRational(left.getNumerator().gcd((right.getNumerator()))); } } 

BigRational包含BigInteger分子和分母。 如果简化比率的分母等于1,则isInteger()返回true。