如何制作简化分数的Java方法?

时间:2013-02-19 18:42:17

标签: java simplify fractions

我已经编写了一个Fraction类,并且在简化方面遇到了麻烦。

当我制作Fraction对象时,一切正常,我认为我的逻辑很简单。

(num和den分别是分类和分母类中的私有变量)

以下是我的GCD和简化方法:

/**
 * Returns the absolute value of the greatest common divisor of this
 * fraction's numerator and denominator. If the numerator or denominator is
 * zero, this method returns 0. This method always returns either a positive
 * integer, or zero.
 * 
 * @return Returns the greatest common denominator
 */
private int gcd() {
    int s;
    if (num > den)
        s = den;
    else
        s = num;
    for (int i = s; i > 0; i--) {
        if ((num % i == 0) && (den % i == 0))
            return i;
    }
    return -1;
}

/**
 * Changes this fraction's numerator and denominator to "lowest terms"
 * (sometimes referred to as a "common fraction"), by dividing the numerator
 * and denominator by their greatest common divisor. This includes fixing
 * the signs. For example, if a fraction is 24/-18, this method will change
 * it to -4/3. If the numerator or denominator of the fraction is zero, no
 * change is made.
 */
public void simplify() {

    if (isZero() == false) {// Making sure num or den is not zero.
        this.fixSigns(); // Fix signs first

        if (gcd() > 1) {
            this.num = num / gcd();
            this.den = num / gcd();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

我立即看到的两件事:对于分子和分母中的每一个,您将num除以gcd()两次。此外,一旦您更改分子,则调用gcd()的结果可能会发生变化。调用“gcd”一次,存储结果,稍后再使用:

int gcd = gcd();
if (gcd > 1) {
   this.num = this.num / gcd;
   this.den = this.den / gcd;
}

此外,还有更有效的方法可以获得最大的公约数:Wikipedia's page。请参阅该页面上的Euclid算法。