60.md 2.4 KB
Newer Older
W
wizardforcel 已提交
1
# Kotlin 程序:查找两个数字的 LCM
W
wizardforcel 已提交
2 3 4

> 原文: [https://www.programiz.com/kotlin-programming/examples/lcm](https://www.programiz.com/kotlin-programming/examples/lcm)

W
wizardforcel 已提交
5
#### 在此程序中,您将学习使用 GCD 而不是 GCD 查找两个数字的 lcm。 这是通过 Kotlin 中的`while`循环完成的。
W
wizardforcel 已提交
6 7 8

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

W
wizardforcel 已提交
9
## 示例 1:使用`while`循环和`if`语句计算 LCM
W
wizardforcel 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

```kt
fun main(args: Array<String>) {
    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.
```

W
wizardforcel 已提交
37
在此程序中,将找到其 LCM 的两个数字分别存储在变量`n1``n2`中。
W
wizardforcel 已提交
38

W
wizardforcel 已提交
39
然后,我们最初将`lcm`设置为两个数字中的最大值。 这是因为 LCM 不能小于最大数量。
W
wizardforcel 已提交
40

W
wizardforcel 已提交
41
与 Java 类似,在无限`while`循环(`while(true)`)中,我们检查`lcm`是否完美地划分了`n1``n2`
W
wizardforcel 已提交
42

W
wizardforcel 已提交
43
如果是这样,我们已经找到 LCM。 我们打印 LCM 并使用`break`语句退出`while`循环。
W
wizardforcel 已提交
44

W
wizardforcel 已提交
45
否则,我们将`lcm`加 1,然后重新测试除数条件。
W
wizardforcel 已提交
46

W
wizardforcel 已提交
47
这是等效的 Java 代码:[查找两个数字的 LCM 的 Java 程序](/java-programming/examples/lcm "How to find LCM of two numbers in Java?")
W
wizardforcel 已提交
48 49 50 51 52 53 54 55 56 57 58

* * *

我们还可以使用 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。

W
wizardforcel 已提交
59
## 示例 2:使用 GCD 计算 LCM
W
wizardforcel 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

```kt
fun main(args: Array<String>) {
    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 相同。

W
wizardforcel 已提交
82
在这里,在`while`循环内,我们计算了两个数字的 GCD - `n1``n2`。 计算后,我们使用上面的公式来计算 LCM。