Java Code Example: least common multiple

The code defines a method gcd to calculate the greatest common divisor (GCD) of two integers. It uses the Euclidean algorithm to find the GCD by repeatedly subtracting the smaller number from the larger number until one of the numbers reaches 0. The GCD is then returned as the non-zero number.

The code also defines a method lcm that calculates the least common multiple (LCM) of two integers by dividing the product of the two numbers by their GCD. The LCM is calculated by the formula a * b / gcd(a, b).

Finally, the main method calls the lcm method with a = 10 and b = 6 and prints the result, which is 30, the LCM of 10 and 6.

public class LeastCommonMultiple {
    static int gcd(int a, int b) {
        if (a == 0) {
            return b;
        } else if (b == 0) {
            return a;
        } else if (a > b) {
            return gcd(a - b, b);
        } else {
            return gcd(a, b - a);

    static int lcm(int a,int b) {
        return a * b / gcd( a, b);

    public static void main(String[] args) {
        int a = 10, b = 6;

        System.out.println("Least common multiple is: " + lcm(a, b));
Least common multiple is: 30