Find GCD and LCM using Java

Overview

In this article we will show how to write a Java program to find the GCD and LCM of two numbers. For the GCD we will make use of the Euclid’s theorem. The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number. For example, 21 is the GCD of 252 and 105 (as 252 = 21 × 12 and 105 = 21 × 5), and the same number 21 is also the GCD of 105 and 252 − 105 = 147. Since this replacement reduces the larger of the two numbers, repeating this process gives successively smaller pairs of numbers until the two numbers become equal. When that occurs, they are the GCD of the original two numbers

Euclid’s Theorem

Code

In this section we will see the working code.

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

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

Test

Lets write a simple tests for the above code.

@Test
public void gcd() {
    assertEquals(4, GcdAndLcm.gcd(12, 20));
}

@Test
public void lcm() {
    assertEquals(60, GcdAndLcm.lcm(12, 20));
}

Conclusion

In this article we saw how to find Greatest Common Divisor (GCD) and Lowest Common Multiple (LCM) of two numbers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: