Kotlin 程序查找两个数的 LCM

两个整数的 LCM 是能被这两个数整除(无余数)的最小正整数。

示例 1:使用 while 循环和 if 语句计算 LCM 的 Kotlin 程序

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
    }
}

运行程序后,输出将是

The LCM of 72 and 120 is 360.

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

然后,我们将 lcm 初始化为这两个数字中较大的那个。这是因为 LCM 不能小于较大的数字。

与 Java 类似,在无限 while 循环 (while(true)) 中,我们检查 lcm 是否能同时被 n1n2 整除。

如果可以,我们就找到了 LCM。我们打印 LCM 并使用 break 语句跳出 while 循环。

否则,我们将 lcm 增加 1 并重新测试整除条件。

这是等效的 Java 代码: Java 程序查找两个数的 LCM


我们也可以使用 GCD 来查找两个数的 LCM,方法如下:

LCM = (n1 * n2) / GCD

如果您不知道如何在 Java 中计算 GCD,请查看 Kotlin 程序查找两个数的 GCD

示例 2:使用 GCD 计算 LCM 的 Kotlin 程序

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 相同。

在这里,在 while 循环中,我们计算两个数字 n1n2 的 GCD。计算后,我们使用上述公式计算 LCM。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战