简化 Java 中的分数

2022-09-01 18:10:05

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

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

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);
    }  
}

答案 1

有趣的问题。以下是一些使用最少代码完成的可执行代码:

/** @return the greatest common denominator */
public static long gcd(long a, long b) {
    return b == 0 ? a : gcd(b, a % b);
}

public static String asFraction(long a, long b) {
    long gcd = gcd(a, b);
    return (a / gcd) + "/" + (b / gcd);
}

// Some tests
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"
}

奖金方式:

/** @return the lowest common multiple */
public static long lcm(long a, long b) {
    return a * b / gcd(a, b);
}

/** @return the greatest common denominator */
public static long gcd(List<? extends Number> numbers) {
    return numbers.stream().map(Number::longValue).reduce((a, b) -> gcd(a, b)).orElseThrow(NoSuchElementException::new);
}

/** @return the lowest common multiple */
public static long lcm(List<? extends Number> numbers) {
    return numbers.stream().map(Number::longValue).reduce((a, b) -> lcm(a, b)).orElseThrow(NoSuchElementException::new);
}

答案 2

您需要 GCD。要么像Nathan提到的那样使用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,你应该创建一个新函数。只是让它更干净一点,更容易阅读。您也可以测试该函数。


推荐