Tuesday, August 31, 2010

How to find gcd and lcm in Java

Here is the easiest and efficient way to get the Greatest Common Divisor(gcd) and Least Common Multiple(lcm) in Java. This algorithm could be used for any language. Here I have used Long data type. You can use integer as needed.

public static long gcd(long a, long b) {
if (b==0)
return a;
else
return gcd(b, a % b);
}

public static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}

Least Common Multiple

No comments:

Post a Comment