# Kotlin 程序:查找两个数字的 LCM > 原文: [https://www.programiz.com/kotlin-programming/examples/lcm](https://www.programiz.com/kotlin-programming/examples/lcm) #### 在此程序中,您将学习使用 GCD 而不是 GCD 查找两个数字的 lcm。 这是通过 Kotlin 中的`while`循环完成的。 两个整数的 LCM 是可以被两个数字完全除(没有余数)的最小正整数。 ## 示例 1:使用`while`循环和`if`语句计算 LCM ```kt fun main(args: Array) { val n1 = 72 val n2 = 120 var lcm: Int // maximum number between n1 and n2 is stored in lcm lcm = if (n1 > n2) n1 else n2 // Always true while (true) { if (lcm % n1 == 0 && lcm % n2 == 0) { println("The LCM of $n1 and $n2 is $lcm.") break } ++lcm } } ``` 运行该程序时,输出为: ```kt The LCM of 72 and 120 is 360. ``` 在此程序中,将找到其 LCM 的两个数字分别存储在变量`n1`和`n2`中。 然后,我们最初将`lcm`设置为两个数字中的最大值。 这是因为 LCM 不能小于最大数量。 与 Java 类似,在无限`while`循环(`while(true)`)中,我们检查`lcm`是否完美地划分了`n1`和`n2`。 如果是这样,我们已经找到 LCM。 我们打印 LCM 并使用`break`语句退出`while`循环。 否则,我们将`lcm`加 1,然后重新测试除数条件。 这是等效的 Java 代码:[查找两个数字的 LCM 的 Java 程序](/java-programming/examples/lcm "How to find LCM of two numbers in Java?")。 * * * 我们还可以使用 GCD 通过以下公式查找两个数字的 LCM: ```kt LCM = (n1 * n2) / GCD ``` 如果您不知道如何用 Java 计算 GCD,请检查 [Kotlin 程序以找到两个数字](/kotlin-programming/examples/hcf-gcd "How to find GCD of two numbers in Kotlin?")的 GCD。 ## 示例 2:使用 GCD 计算 LCM ```kt fun main(args: Array) { val n1 = 72 val n2 = 120 var gcd = 1 var i = 1 while (i <= n1 && i <= n2) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) gcd = i ++i } val lcm = n1 * n2 / gcd println("The LCM of $n1 and $n2 is $lcm.") } ``` 该程序的输出与示例 1 相同。 在这里,在`while`循环内,我们计算了两个数字的 GCD - `n1`和`n2`。 计算后,我们使用上面的公式来计算 LCM。