Albert Albert - 4 months ago 20
Java Question

Java: get greatest common divisor

I have seen that such a function exists for

BigInteger
, i.e.
BigInteger#gcd
. Are there other functions in Java which also works for other types (
int
,
long
or
Integer
)? It seems this would make sense as
java.lang.Math.gcd
(with all kinds of overloads) but it is not there. Is it somewhere else?




(Don't confuse this question with "how do I implement this myself", please!)

Answer

For int and long, as primitives, not really. For Integer, it is possible someone wrote one.

Given that BigInteger is a (mathematical/functional) superset of int, Integer, long, and Long, if you need to use these types, convert them to a BigInteger, do the GCD, and convert the result back.

private static int gcdThing(int a, int b) {
    BigInteger b1 = new BigInteger(""+a); // there's a better way to do this. I forget.
    BigInteger b2 = new BigInteger(""+b);
    BigInteger gcd = b1.gcd(b2);
    return gcd.intValue();
}

The better way:

private static int gcdThing(int a, int b) {
    BigInteger b1 = BigInteger.valueOf(a);
    BigInteger b2 = BigInteger.valueOf(b);
    BigInteger gcd = b1.gcd(b2);
    return gcd.intValue();
}
Comments