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

1 comment:

  1. Please, I need your help.
    Write a class named Euclidean and in the class write a method with the signatures. Public long gcd(long m,long n)
    Write another class called public long lcm (long m,long n) create an object of Euclidean and invoke gcd to implement the lcm. Finally write a class called mainApp that implements the main method. It should accept two integer from the user via input diologue boxes, calculated their lcm and display it an output on the box. Slyokoh@yahoo.com

    ReplyDelete