Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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!)

like image 917
Albert Avatar asked Oct 24 '10 16:10

Albert


People also ask

Does Java have a GCD function?

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).

What is GCD in Java?

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).


1 Answers

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.

like image 160
Matt Avatar answered Oct 05 '22 22:10

Matt