简化Java中的分数

Par*_*han 21 java rational-numbers simplification

我的任务是发展一个理性的阶级.如果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);
    }  
}
Run Code Online (Sandbox Code Playgroud)

Boh*_*ian 42

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

/** @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"
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 13

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

public int GCD(int a, int b){
   if (b==0) return a;
   return GCD(b,a%b);
}
Run Code Online (Sandbox Code Playgroud)

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

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

whole = x/y;
numerator x%y;
denominator = y;
Run Code Online (Sandbox Code Playgroud)

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

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

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


Paŭ*_*ann 5

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

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

while (n1 != 0 && n2 != 0){
  if(n1 > n2)
     n1 = n1 % n2;
  else
     n2 = n2 % n1;
}
Run Code Online (Sandbox Code Playgroud)

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

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

while(n1 != 0) {
   int old_n1 = n1;
   n1 = n2 % n1;
   n2 = old_n1;
}
Run Code Online (Sandbox Code Playgroud)

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