Search code examples
javadouble

Java greater common divisor with big double values


I'm trying to implement a gcd with doubles.

Here's my code:

public static double doubleGcd(double n1, double n2) {
    if (n2 != 0)
        return doubleGcd(n2, n1 % n2);
    else
        return n1;
}

It works well, until I test it with some big values.

As an example I've using:

  • n1: Math.pow(10,25)
  • n2: 14400

The GCD is 1600 but my code return 64.

I think the cause is the modulo operator and the fact the values are too big, but I can't figure out how to change the code to make it works.


Solution

  • I was able to solve my problem by using BigDecimal instead of Double type.

    Here's my new Code:

    public static BigDecimal Gcd(BigDecimal n1, BigDecimal n2) {
        if (n2.compareTo(new BigDecimal(0)) != 0)
            return Gcd(n2, n1.remainder(n2));
        else
            return n1;
    }
    

    Bigdecimal .remainder() is not the same as modulo operation, but in this case it works as well.

    Docs: BigDecimal.remainder()