I have seen that such a function exists for BigInteger
, i.e. BigInteger#gcd
. Are there other functions in Java which also work 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!)
Java BigInteger gcd() methodThe gcd() method of Java BigInteger class is used to get the greatest common divisor of absolute values of two BigInteger. This method returns a BigInteger whose value is the greatest common divisor of abs (this) and abs (val).
GCD (Greatest Common Divisor) of two given numbers A and B is the highest number that can divide both A and B completely, i.e., leaving remainder 0 in each case. GCD is also called HCF(Highest Common Factor).
As far as I know, there isn't any built-in method for primitives. But something as simple as this should do the trick:
public int gcd(int a, int b) { if (b==0) return a; return gcd(b,a%b); }
You can also one-line it if you're into that sort of thing:
public int gcd(int a, int b) { return b==0 ? a : gcd(b, a%b); }
It should be noted that there is absolutely no difference between the two as they compile to the same byte code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With