私の仕事は、合理的なクラスを開発することです。 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を使用するか、使用できない場合は自分で使用してください。
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を検索する場合は、おそらく新しい関数を作成する必要があります。少しすっきりとして読みやすくします。また、その機能をテストすることもできます。
参考までに、実装したのは元のsubtractiveユークリッドアルゴリズム最大公約数 を計算するためです== 2つの数の。
より高速なバージョンでは、整数除算の残りを使用しています。 %
の代わりに -
ループ内:
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
はBigInteger
のgcd
関数を使用します。
_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を返します。