Skip to content

Latest commit

 

History

History
83 lines (57 loc) · 2.39 KB

File metadata and controls

83 lines (57 loc) · 2.39 KB

Java 程序:查找两个数字的 LCM

原文: https://www.programiz.com/java-programming/examples/lcm

在此程序中,您将学习使用 GCD 而不是 GCD 查找两个数字的 lcm。 这是使用 Java 中的forwhile循环完成的。

两个整数的 LCM 是可以被两个数字完全除(没有余数)的最小正整数。

示例 1:使用while循环和if语句的 LCM

public class LCM {
    public static void main(String[] args) {

        int n1 = 72, n2 = 120, lcm;

        // maximum number between n1 and n2 is stored in lcm
        lcm = (n1 > n2) ? n1 : n2;

        // Always true
        while(true)
        {
            if( lcm % n1 == 0 && lcm % n2 == 0 )
            {
                System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
                break;
            }
            ++lcm;
        }
    }
} 

运行该程序时,输出为:

The LCM of 72 and 120 is 360.

在此程序中,将找到其 LCM 的两个数字分别存储在变量n1n2中。

然后,我们最初将lcm设置为两个数字中的最大值。 这是因为 LCM 不能小于最大数量。

在无限while循环(while(true))内,我们检查lcm是否完美地划分了n1n2

如果是这样,我们已经找到 LCM。 我们打印 LCM 并使用break语句退出while循环。

否则,我们将lcm加 1,然后重新测试除数条件。


我们还可以使用 GCD 通过以下公式查找两个数字的 LCM:

LCM = (n1 * n2) / GCD

如果您不知道如何用 Java 计算 GCD,请检查 Java 程序以找到两个数字的 GCD。

示例 2:使用 GCD 计算 LCM

public class LCM {
    public static void main(String[] args) {

        int n1 = 72, n2 = 120, gcd = 1;

        for(int i = 1; i <= n1 && i <= n2; ++i)
        {
            // Checks if i is factor of both integers
            if(n1 % i == 0 && n2 % i == 0)
                gcd = i;
        }

        int lcm = (n1 * n2) / gcd;
        System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
    }
} 

该程序的输出与示例 1 相同。

在这里,在for循环内,我们计算两个数字的 GCD - n1n2。 计算后,我们使用上面的公式来计算 LCM。