Albert - 9 months ago 57

Java Question

I have seen that such a function exists for

`BigInteger`

`BigInteger#gcd`

`int`

`long`

`Integer`

`java.lang.Math.gcd`

(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();
}
```