大数字GCD

时间:2016-12-18 23:52:06

标签: java greatest-common-divisor

我正在开展一个项目,该项目涉及使用方程组来求解某些半径。我的方法似乎工作正常,但要返回正确的答案,我需要以最简单的形式返回一个比率。所以24/2会以12/1的形式返回,它存储在一个数组中。所以最终的答案是[12,1]。

对于运作良好的数字,我没有任何困难。但有时会有半径为843.667,我需要将其作为最基本的部分返回。这就是我被难倒的地方,因为我无法弄清楚如何去做。要么我得到有损转换错误,错误的数字,要么只是零。

//Class set-up to be given a double and return both its numerator and denominator
class Rational {
    public int num, denom;
    //Establishes both the numerator and denominator 
    public Rational(int num, int denom) {
        this.num = num;
        this.denom = denom;
    }

    public Rational(double d) {
        //Split up the number, so that we have the integer value and decimal value
        long i = (long) Math.ceil(d);
        double numerator = d - i;
        // Know how many decimal places we are dealing with and establish a proper numerator and denominator 
        String frac = new Double(numerator).toString();
        frac = frac.substring(frac.indexOf('.'));
        numerator = Double.parseDouble(frac);
        int power = frac.length();
        double denominator = Math.pow(10, power);

        //Find the GCD of the numerator and denominator 
        double gcd = findGCD((int) numerator, (int) denominator);
        numerator /= gcd;
        denominator /= gcd;
        this.num = (int) numerator;
        this.denom = (int) denominator;
    }

   // Method to find the GCD of two int values
   public static int findGCD(int n1, int n2) {
        while (n1 != n2) {
            if (n1 > n2) {
                n1 = n1 - n2;
            } else {
                n2 = n2 - n1;
            }
        }
        return n1;
    }
}

如果你可以帮助弄清楚我的843.667如何变成一个分数,那就太棒了。

0 个答案:

没有答案