Showing posts with label Algorithms. Show all posts
Showing posts with label Algorithms. Show all posts

Saturday, January 10, 2009

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;
}