GCD of Large Numbers

531 views Asked by At

I'm working on a project that involves using a system of equations to solve for certain radii. My method for that seems to be working fine, but to return the correct answer I need to return a ratio in the simpilest form. So 24/2 would come back as 12/1, which is stored in an array. So the final answer would be [12,1].

For numbers that work nicely I have no difficulty. But there are times when there will be radii that are 843.667 and I need to return this as the most basic fraction. And this is where I'm getting stumped because I cant figure out how to do it. Either I get a lossy conversion error, the wrong number, or just zeros.

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

If you can help figure out how my 843.667 could be turned into a fraction, that would be amazing.

0

There are 0 answers